dp6319 2018-01-30 12:23
浏览 467
已采纳

Laravel whereBetween在两列中

i need to select products from DB by whereBetween. I have two double type columns in database, price and newprice. Price field is required and newprice is 0 by default. Admin writes newprice if there is any discounts on that product.

Now my problem is it that i need to select from DB with whereBetween by price if newprice == 0 and by newprice if newprice != 0. In a word filter by newprice if it is written, and by price if newprice is 0 by default.

Here is my code.

$from = (int)$request->priceFrom;
$to = (int)$request->priceTo;

$products = Product::whereIn('category_id', $childCategories)->orWhere('category_id', $category->id)->where('publish', 1)->orderBy('created_at', 'desc');
$products->whereBetween('price',array($from,$to))->orWhereBetween('newprice',array($from,$to));
$products = $products->paginate(15);

It doesn't works correctly ofc. Any ideas?

  • 写回答

1条回答 默认 最新

  • dongyin4202 2018-01-30 12:36
    关注

    you can do something like this using laravels parameter grouping

    $products->where(function($query){
         $query->where('new_price', 0)
         ->whereBetween('price', [$from, $to]);
    })->orWhere(function($query){
         $query->where('new_price', '>', 0)
         ->whereBetween('new_price', [$from, $to]);
    })->paginate(15);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?