【问题标题】:Dynamic Relational Query in Laravel EloquentLaravel Eloquent 中的动态关系查询
【发布时间】:2018-06-18 06:06:51
【问题描述】:

我有一个包含动态过滤器的搜索表单,我想根据不同过滤器的存在动态生成关系查询。

使用 whereHas like

$properties = PropertyList::where('varification_status', '1')
    ->whereHas('common_property_details', function ($query) {
        $query->where('no_bathroom', '=', '1');
    })->get();

如何在不使用一堆 if else 语句的情况下填充动态查询

Alexey Mezenin 的回答是正确的,还有一个疑问。 现在我可以使用了

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

但显示出击错误

缺少参数 2 App\Http\Controllers\PropertySearchController::App\Http\Controllers{closure}()

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    如果不想使用大量的if 语句,可以使用when() 方法:

    $properties = PropertyList::where('varification_status', '1')
        ->when($something === $somethingElse, function($q) {
            $q->whereHas(....);
        })
        ->when($something > $someMaximum, function($q) {
            $q->whereHas(....);
        })
        ->get();
    

    【讨论】:

    • @RahulReghunath 您需要使用 use() 将变量传递到闭包范围。例如whereHas(function($q) use($bathRoom) { .... })
    猜你喜欢
    • 2013-10-03
    • 2017-07-19
    • 2021-09-25
    • 2015-01-21
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多