亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何用 eloquent 編寫查詢,就像 SQL 中的括號一樣?

如何用 eloquent 編寫查詢,就像 SQL 中的括號一樣?

PHP
瀟瀟雨雨 2022-01-08 20:41:38
我有一個查詢,其中所有參數都是可選的 我想在以下情況下選擇行:“選擇所有具有 marketplace_id 或 account_id 并具有標題的產品”。換一種說法 select * from produts where (marketplace_id in (...) or account_id in (...)) and title ilike "blah".那是我能到的最遠的地方。   $query = Product::query();    if($parametros_pesquisa['marketplaces'] !== null )    {       $query->whereIn('marketplace_id', $search_parameters['marketplaces']);    }if($parametros_pesquisa['contas'] !== null){                 $query->orWhereIn('conta_id', $search_parameters['account']);    } if($search_parameters['titulo'] !== null){        $query->where("titulo", 'ilike', '%' . $search_parameters['titulo'] . '%');   }在這里,$search_parameters['marketplaces']and$search_parameters['account']將是一個 id 數組,[1, 2, 3]。我檢查用戶是否指定了搜索條件并將其動態包含在查詢中。似乎查詢正在執行,就像查詢中的括號不存在一樣。我怎樣才能達到我想要的?
查看完整描述

2 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

您可以將回調傳遞where給 group or。


//quick example of Parameter Grouping:


$query = Product::query();


$query->where(function ($query) use ($search_parameters){

     $query->whereIn('marketplace_id', $search_parameters['marketplaces'])->orWhereIn('conta_id', $search_parameters['account']);

})->where("titulo", 'ilike', '%' . $search_parameters['titulo'] . '%');

請閱讀 DB Query Builder Laravel: DOCS


查看完整回答
反對 回復 2022-01-08
?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

答案指明了方向。我能夠查看是否傳遞了參數并動態添加條件。


 $query->where(function ($query) use ($parametros_pesquisa){


            if($parametros_pesquisa['marketplaces'] !== null && $parametros_pesquisa['accounts'] !== null){


                $query->whereIn('marketplace_id', json_decode( $parametros_pesquisa['marketplaces']))->orWhereIn('conta_id', json_decode( $parametros_pesquisa['accounts']));


            }elseif($parametros_pesquisa['marketplaces'] !== null){


                $query->whereIn('marketplace_id', json_decode( $parametros_pesquisa['marketplaces']));


            }elseif($parametros_pesquisa['accounts']  !== null){


                $query->whereIn('conta_id', json_decode( $parametros_pesquisa['accounts']));


            }


       });


查看完整回答
反對 回復 2022-01-08
  • 2 回答
  • 0 關注
  • 148 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號