【问题标题】:filter with Eloquent用 Eloquent 过滤
【发布时间】:2021-05-12 02:54:15
【问题描述】:

我有 2 个表格:测试、问题,我想显示测试的激活问题:

$test = Test::whereHas('questions', function(Builder $query){
            $query->where('activated','=','1');
        })->find($id);

但我得到了问题;激活和停用。

感谢您的帮助。

【问题讨论】:

    标签: laravel laravel-5 eloquent eloquent-relationship


    【解决方案1】:

    您正在获取所有已激活问题的测试。

    但是当得到 $test 的结果时,您可能会获取 all 关系为 $test->questions 的问题。

    如果您只想获取激活的问题,您可以在 $test 对象上执行以下操作:

    $test = Test::whereHas('questions', function(Builder $query){
                $query->where('activated','=','1');
            })->find($id);
    
    $questions = $test->questions()->where('activated', '1')->get();
    

    加载激活的问题:

    $test = Test::whereHas('questions', function(Builder $query){
                $query->where('activated','=','1');
            })->with(['questions' => function ($query) {
        $query->where('activated', '1');
    }])->find($id);
    
    // Will only give you the activated questions
    var_dump($test->questions);
    

    或者您可以在测试模型中定义自定义关系,为您进行过滤。

    【讨论】:

    • 感谢您的回答,但我正在寻找可以拥有一个有效负载的结果。例如:test { "name": "a", "questions": [{id:"1", "activated": 1},{id:"2", "activated": 1}]}
    • 添加了另一个示例 - 但可以看到 @gbalduzzi 在 4 分钟前添加了相同的示例
    • 你可以重复使用闭包whereHas('questions', $f = function (...) {...})->with(['questions' => $f]) btw
    【解决方案2】:

    当您使用whereHas 时,您是在告诉 eloquent 只选择具有至少一个已激活问题的测试。但是您并没有告诉它只保留激活的问题:您可以使用constrained eager loading 来实现:

    $test = Test::with(['questions' => function(Builder $query){
                $query->where('activated','=','1');
            }])->find($id);
    

    【讨论】:

    • 不幸的是我得到一个错误 App\Http\Controllers\API\{closure}() must be an instance of Illuminate\Database\Eloquent\Builder, instance of Illuminate\Database\Eloquent\Relations\HasMany给定
    • 删除Builder
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2014-09-18
    • 2023-03-10
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多