我有以下
HTML
<input type="checkbox" name="symbols[]" value="1" />
<input type="checkbox" name="symbols[]" value="2" />
<input type="checkbox" name="symbols[]" value="3" />
etc...
<select name="city">
<option value="Dublin">Dublin</option>
<option value="Cork">Cork</option>
etc ...
</select>
Laravel
return DB::table('restaurants')
->select('restaurants.id as restaurantId',
'restaurants.image_id as imageId',
'restaurants.name as restaurantName',
'restaurants.slug as restaurantSlug',
'restaurants.description as restaurantDescription')
->leftJoin('restaurants_symbols', 'restaurants_symbols.restaurant_id', '=', 'restaurants.id')
->leftJoin('restaurants_locations', 'restaurants_locations.restaurant_id', '=', 'restaurants.id')
->groupBy('restaurants_symbols.restaurant_id')
->where(function($q) use ($input) {
$q->whereIn('restaurants_symbols.symbol_id', $input['symbol']);
if(!empty($input['city'])) {
$q->where('restaurants_locations.city', $input['city']);
}
})
->get();
如果用户选中了value1和value2,那么查询将返回包含value1或value2的所有餐馆,所以我想实现的只是返回只有代表value1 AND value2的符号的餐馆。 / p>
有什么建议吗?我想也许可以按原样返回值,然后在foreach循环中过滤它们但是我不知道它是否可能,如果它是我没有看到如何做到这一点的逻辑,对此的任何想法?
答案 0 :(得分:0)
试试这个..
用于for condition的where循环。它为你的case返回value1和value2
$symbol=$input['symbol'];
return DB::table('restaurants')
->select('restaurants.id as restaurantId',
'restaurants.image_id as imageId',
'restaurants.name as restaurantName',
'restaurants.slug as restaurantSlug',
'restaurants.description as restaurantDescription')
->leftJoin('restaurants_symbols', 'restaurants_symbols.restaurant_id', '=', 'restaurants.id')
->leftJoin('restaurants_locations', 'restaurants_locations.restaurant_id', '=', 'restaurants.id')
->groupBy('restaurants_symbols.restaurant_id')
->where(function($q) use ($input) {
for($i=0;$i<count($symbol);$i++) //add forloop
{
$q->where('restaurants_symbols.symbol_id', $symbol[$i]);
}
if(!empty($input['city'])) {
$q->where('restaurants_locations.city', $input['city']);
}
})
->get();