How to access model hasMany Relation with where condition?

前端 未结 8 1377
迷失自我
迷失自我 2020-12-08 00:02

I created a model Game using a condition / constraint for a relation as follows:

class Game extends Eloquent {
             


        
8条回答
  •  甜味超标
    2020-12-08 00:46

    I have fixed the similar issue by passing associative array as the first argument inside Builder::with method.

    Imagine you want to include child relations by some dynamic parameters but don't want to filter parent results.

    Model.php

    public function child ()
    {
        return $this->hasMany(ChildModel::class);
    }
    

    Then, in other place, when your logic is placed you can do something like filtering relation by HasMany class. For example (very similar to my case):

    $search = 'Some search string';
    $result = Model::query()->with(
        [
            'child' => function (HasMany $query) use ($search) {
                $query->where('name', 'like', "%{$search}%");
            }
        ]
    );
    

    Then you will filter all the child results but parent models will not filter. Thank you for attention.

提交回复
热议问题