Laravel使用"if"查询情况? [英] Laravel query with "if" conditions?
本文介绍了Laravel使用"if"查询情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Laravel 4创建一个高级搜索表单,这是查询:
I'm trying to make an advanced search form with Laravel 4, and this is the query:
$result = DB::table('users_ads')
->join('ads', 'users_ads.ad_id', '=', 'ads.id')
->orderBy($column, $method)
->where('status', TRUE)
->where(function($query) use ($input)
{
$query->where('short_description', $input['search'])
->where('category', $input['category'])
->where('product', $input['product']);
})
->join('users', 'users_ads.user_id', '=', 'users.id')
->select('ads.id', 'ads.img1', 'ads.short_description', 'ads.category', 'ads.product', 'ads.price', 'users.city')
->get();
return $result;
问题是用户可能不会使用所有输入字段.所以我想在这部分包括一些条件:
The problem is that the user might not use all the input fields. So i want to include some if conditions in this part:
$query->where('short_description', $input['search'])
->where('category', $input['category'])
->where('product', $input['product']);
..因此,如果输入为空,则删除"where"条件.
.. so if the input is empty, to remove the "where" condition.
推荐答案
$filters = [
'short_description' => 'search',
'category' => 'category',
'product' => 'product',
];
.....
->where(function($query) use ($input, $filters)
{
foreach ( $filters as $column => $key )
{
$value = array_get($input, $key);
if ( ! is_null($value)) $query->where($column, $value);
}
});
较新版本的Laravel具有when
方法,这使此操作变得更加容易:
Newer version of Laravel have a when
method that makes this much easier:
->where(function ($query) use ($input, $filters) {
foreach ($filters as $column => $key) {
$query->when(array_get($input, $key), function ($query, $value) use ($column) {
$query->where($column, $value);
});
}
});
这篇关于Laravel使用"if"查询情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文