[英]How to make a whereIn query builder in Laravel Eloquent with empty parameter
I have made a query in Laravel Eloquent to search in table. 我在Laravel Eloquent中进行了查询以在表中进行搜索。
public function searchContest($search){
$category = [];
$area = [];
if(isset($search['area'])){
$area = $search['area'];
}
if(isset($search['category'])){
$category = $search['category'];
}
$qry = self::whereIn('area',$area)
->whereIn('category', $category)
->get();
var_dump($query);
return;
}
But sometimes, area
or category
is empty and whereIn
does not work with it. 但有时,
area
或category
为空,而whereIn
不能使用。 I'm not able to find any working solutions in the net. 我无法在网络上找到任何有效的解决方案。 How can I make such a query?
我该如何查询?
Or you can take advantage of the conditional clauses as here 或者您可以利用此处的条件条款
DB::table('table_name')
->when(!empty($category), function ($query) use ($category) {
return $query->whereIn('category', $category);
})
->when(!empty($area), function ($query) use ($area) {
return $query->whereIn('area', $area);
})
->get();
$q = self::query();
if (isset($search['area'])) {
$q->whereIn('area', $search['area']);
}
if (isset($search['category'])) {
$q->whereIn('category', $search['category']);
}
$qry = $q->get();
You can use query scope inside the entity 您可以在实体内部使用查询范围
public function scopeArea($query, $ids)
{
if (! $ids) {
return ;
}
return $query->whereIn('area', $ids);
}
public function scopeCategory($query, $ids)
{
if (! $ids) {
return ;
}
return $query->whereIn('category', $ids);
}
Now you can build the query 现在您可以建立查询
$entity
->area($area)
->category($category)
->get();
https://laravel.com/docs/5.7/eloquent#query-scopes https://laravel.com/docs/5.7/eloquent#query-scopes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.