问题描述
您好,我想获取排除空值关系的记录。我尝试了很多代码,但没有正确解决。这是我的尝试之一:
$product= [];
$product= Product::select('id','ref_num','eta','customer_id')
->when(count($customer_ids) > 0,function($q) use ($customer_ids){
return $q->whereIn('customer_id',$customer_ids);
})
->when(!is_null($ref_num_q_string) && $ref_num_q_string !=='',function($q) use ($ref_num_q_string){
return $q->where('ref_num','like','%'.$ref_num_q_string.'%');
})
->with(['customer' => function($q){
$q->select('id','company_name');
}])
// ->whereExists(function($q){
// $q->select('id','product_id','total_amount')
// ->from('bills')
// ->whereColumn('bills.product_id','products.id');
// })
// ->whereExists(function($q){
// $q->select('id','total_amount')
// ->from('invoices')
// ->whereColumn('invoices.product_id','products.id');
// })
->with(['bill' => function($q){
$q->with(['bill_items']);
$q->select('id','total_amount');
}])
->with(['invoice' => function($q){
$q->with(['invoiceServices']);
$q->select('id','total_amount');
}])
->has('invoice')
->orHas('bill')
->orderBy($sort_by,$sort_type)
->paginate(isset($per_page) ? $per_page : 50);
我在搜索过滤器中使用了“when”子句。 如果我有 1 个“has”方法,它会返回正确的值,但是当我添加“orHas”时,问题就出现了,它会返回与字符串匹配的记录,但其他不必要的记录也在其中。
解决方法
所以 orHas
和 orWhere
会给您带来一些问题。这些将导致查询的其余部分出现问题,这意味着不会考虑您的其他条件。您需要在 ->has()
上使用类似于以下内容的闭包:
->has(function ($query) {
$query->has('invoice')
->orHas('bill');
})
->orderBy($sort_by,$sort_type)
->paginate(isset($per_page) ? $per_page : 50);
现在,您将只获得包含发票或帐单的行的结果。
在此处查看文档:{{3}}