【问题标题】:How can I used "if" condition in "whereIn" in laravel如何在 laravel 的“whereIn”中使用“if”条件
【发布时间】:2017-04-28 09:27:57
【问题描述】:

以下是我使用的查询,并且对我来说工作正常。

    if($t_requested['category_id'])
    {
        $t_query_condition['p.category_id'] = $t_requested['category_id'];
    }
    if($t_requested['brand_id'])
    {
        $t_query_condition['p.brand_id'] = $t_requested['brand_id'];
    }

    $browseData = DB::table('products as p')
        ->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
        ->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
        ->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
               'p.short_description','p.product_price','p.special_price','p.stock_quantity')
        ->orderBy('p.created_by', "desc")
        ->offset(0)
        ->limit(10)
        ->where($t_query_condition)
        ->get();

但现在我在“category_id”和“brand_id”中有多个 id,我想使用 whereIn 但它使用了 of 条件。如果我得到 category_id 或 brand_id 为空,则跳过。

提前致谢。

【问题讨论】:

  • Manish Patoliya: laravel 5.2 ??
  • 不,它在 5.4 @KetanAkbari

标签: php jquery model-view-controller laravel-5.2


【解决方案1】:

试试这个查询希望你能得到结果

        $browseData = DB::table('products as p')
       ->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
               'p.short_description','p.product_price','p.special_price','p.stock_quantity')

        ->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
        ->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
        ->orderBy('p.created_by', "desc");
       if($t_requested['category_id'])
         {
          $browseData->whereIn('p.category_id',$t_requested['category_id']);
         }
      if($t_requested['brand_id'])
         {
         $browseData->whereIn('p.brand_id',$t_requested['brand_id']);
         }

      $result=browseData->offset(0)->limit(10)->get();

【讨论】:

    【解决方案2】:

    我认为这很简单,你必须传递一组值而不是一个值

    我已经尝试编写选项来实现这一点,你必须遵循适合你的选项

    if($t_requested['category_id'])
    {
       $t_query_condition['p.category_id'] = $t_requested['category_id']; // it should be array OR
    
       $t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
    
    $t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
    
    $t_query_condition['p.category_id'] = [$t_requested['category_id']]; // if you want to convert one value into array
            }
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多