Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel Eloquent中的动态关系查询_Laravel_Eloquent - Fatal编程技术网

Laravel Eloquent中的动态关系查询

Laravel 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();

我有一个具有动态过滤器的搜索表单,我希望根据不同过滤器的存在动态生成关系查询

使用whereHas like

$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();