通过Laravel查询构建转换SQL

时间:2019-05-15 17:39:10

标签: sql laravel

我想将以下sql语句转换为Laravel查询构建:

SELECT 
  * 
FROM 
  view_orderline_manifest_data 
where 
  OrderID = 7 
  and (
    ProdCategoryParentID != 4 
    or ProdCategoryParentID IS NOT NULL
  )

尝试了以下内容:

$orderlinedata=DB::table('view_orderline_data')
       ->select('ProdName','ProdID')->where('CustID',$CustID)
       ->where('OrderID',$OrderID)
       ->where('ProdCategoryParentID','!=' , 4)
       ->orWhereNull('ProdCategoryParentID')
       ->pluck('ProdName','ProdID')->all();

问题是正在执行以下操作:

SELECT 
  * 
FROM 
  view_orderline_manifest_data 
where 
  OrderID = 7 
  and ProdCategoryParentID != 4 
  or ProdCategoryParentID IS NOT NULL

基本上没有使用括号()。

2 个答案:

答案 0 :(得分:2)

要获得所需的结果,您需要将闭包传递给代码中的第二个where

$orderlinedata=DB::table('view_orderline_data')
       ->select('ProdName','ProdID')->where('CustID',$CustID)
       ->where('OrderID',$OrderID)
       ->where(function ($query) {
           $query->where('ProdCategoryParentID','!=' , 4)
                 ->orWhereNull('ProdCategoryParentID');
       })
       ->pluck('ProdName','ProdID')->all();

Laravel documentation on Parameter Grouping with the query builder

希望对您有帮助!

答案 1 :(得分:0)

$orderlinedata = ViewOrderlineData::where('CustID',$CustID)
                                  ->where('OrderID', $OrderID)
                                  ->where(function ($query){
                                          $query->where('ProdCategoryParentID', '!=', 4)
                                                  ->orWhereNull('ProdCategoryParentID');
                                      })->pluck('ProdName','ProdID');