【问题标题】:How to write a query in eloquent that is like parentheses in SQL?如何用 eloquent 编写查询,就像 SQL 中的括号一样?
【发布时间】:2020-01-15 16:05:38
【问题描述】:

我有一个查询,其中所有参数都是可选的 我想在以下情况下选择行:“选择所有具有市场 ID 或帐户 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']$search_parameters['account'] 将是一个 id 数组 [1, 2, 3]。我检查用户是否指定了搜索条件并将其动态包含在查询中。似乎查询正在执行,就像查询中的括号不存在一样。我怎样才能达到我想要的?

【问题讨论】:

    标签: php postgresql eloquent


    【解决方案1】:

    您可以将回调传递给where 以分组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

    【讨论】:

      【解决方案2】:

      答案指明了方向。我能够查看是否传递了参数并动态添加条件。

       $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']));
      
                  }
      
             });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-23
        • 1970-01-01
        • 2019-02-21
        • 2014-10-13
        相关资源
        最近更新 更多