【问题标题】:How to use laravel where clause?如何使用 laravel where 子句?
【发布时间】:2019-11-07 19:06:13
【问题描述】:

我是 Laravel 的新手。 如何将以下查询转换为 Laravel 的 where 子句。

where category='1' and (shipping_from='1' OR shipping_to='2')

【问题讨论】:

标签: php laravel


【解决方案1】:

您应该使用嵌套参数分组:https://laravel.com/docs/5.6/queries#parameter-grouping。例如:

->where('category','1')
->where(function ($query) {
            $query->where('shipping_from', '1')
                  ->orWhere('shipping_to', '2');
        })

【讨论】:

  • 我正在使用这样的地方。 $products = Product::where('')
  • 所以你可以这样编码: $products = Product::where('category','1') ->where(function ($query) { $query->where('shipping_from' , '1') ->orWhere('shipping_to', '2'); })->get();
  • 是的,我想像 $products = Product::where('') 进行编码
【解决方案2】:
->where('category', 1)
->where(function ($query){
     $query->where('shipping_from', 1)
           ->orWhere('shipping_to', 2);
})

参考:Parameter Grouping

【讨论】:

  • 我在这样的地方使用。 $products = Product::where('') –
【解决方案3】:

请查看parameter-grouping in Laravel 5.7的文档

$products = Product::where('category', 1)
            ->where(function ($query){
                $query->where('shipping_from', 1)
                      ->orWhere('shipping_to', 2);
            })->get();

最初,laravel 在所有 where 条件中考虑 AND 条件。除非你指定or

【讨论】:

    【解决方案4】:

    你也可以这样尝试:-

    use App\Model;
    
    $data = Model::where('category','1')
                    ->where(function ($query) {
                     $query->where('shipping_from', '1')
                     ->orWhere('shipping_to', '2');
                     })->get();
    

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 2022-10-08
      • 2019-09-08
      • 1970-01-01
      • 2020-11-28
      • 2017-11-30
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      相关资源
      最近更新 更多