[英]How can I used “if” condition in “whereIn” in laravel
以下是我使用的查询,对我来说很好用。
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但它与condition一起使用。 如果我得到category_id或brand_id为null,则跳过。
提前致谢。
试试这个查询,希望你能得到结果
$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();
我认为这很简单,您必须传递值数组而不是一个值
我已经尝试编写实现此目的的选项,您必须遵循适合您的选项
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.