Laravel Eloquent中的动态关系查询
我有一个具有动态过滤器的搜索表单,我希望根据不同过滤器的存在动态生成关系查询 使用whereHas likeLaravel Eloquent中的动态关系查询,laravel,eloquent,Laravel,Eloquent,我有一个具有动态过滤器的搜索表单,我希望根据不同过滤器的存在动态生成关系查询 使用whereHas like $properties = PropertyList::where('varification_status', '1') ->whereHas('common_property_details', function ($query) { $query->where('no_bathroom', '=', '1'); })->get();
$properties = PropertyList::where('varification_status', '1')
->whereHas('common_property_details', function ($query) {
$query->where('no_bathroom', '=', '1');
})->get();
如何在不使用一堆if-else语句的情况下填充动态查询
亚历克赛·梅泽宁的回答是正确的,还有一个疑问。
现在我可以使用
$properties = PropertyList::where('varification_status', '1')
->when($request['bathRooms'] > 0, function ($q) {
$q->whereHas('common_property_details', function ($query) {
$query->where('no_bathroom', '1');
});
})->get();
但是我不能在whereHas中使用任何变量的内部查询
我试过这个
$properties = PropertyList::where('varification_status', '1')
->when($request['bathRooms'] > 0, function ($q) {
$q->whereHas('common_property_details', function ($query,$bathRoom) {
$query->where('no_bathroom', $bathRoom);
});
})->get();
但显示打击错误
第二个论点缺失
App\Http\Controllers\PropertySearchController::App\Http\Controllers{closure}()
如果不想使用大量的
If
语句,可以使用以下方法:
@RahulReghunath您需要使用
use()
将变量传递到闭包范围。例如,whereHas(function($q)use($bathy){……})
$properties = PropertyList::where('varification_status', '1')
->when($something === $somethingElse, function($q) {
$q->whereHas(....);
})
->when($something > $someMaximum, function($q) {
$q->whereHas(....);
})
->get();