Load all relationships for a model

后端 未结 7 973
名媛妹妹
名媛妹妹 2021-01-01 23:58

Usually to eager load a relationship I would do something like this:

Model::with(\'foo\', \'bar\', \'baz\')...

A solution might be to set

7条回答
  •  暖寄归人
    2021-01-02 00:22

    I wouldn't use static methods like suggested since... it's Eloquent ;) Just leverage what it already offers - a scope.

    Of course it won't do it for you (the main question), however this is definitely the way to go:

    // SomeModel
    public function scopeWithAll($query)
    {
        $query->with([ ... all relations here ... ]); 
        // or store them in protected variable - whatever you prefer
        // the latter would be the way if you want to have the method
        // in your BaseModel. Then simply define it as [] there and use:
        // $query->with($this->allRelations); 
    }
    

    This way you're free to use this as you like:

    // static-like
    SomeModel::withAll()->get();
    
    // dynamically on the eloquent Builder
    SomeModel::query()->withAll()->get();
    SomeModel::where('something', 'some value')->withAll()->get();
    

    Also, in fact you can let Eloquent do it for you, just like Doctrine does - using doctrine/annotations and DocBlocks. You could do something like this:

    // SomeModel
    
    /**
     * @Eloquent\Relation
     */
    public function someRelation()
    {
      return $this->hasMany(..);
    }
    

    It's a bit too long story to include it here, so learn how it works: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html

提交回复
热议问题