Load all relationships for a model

后端 未结 7 1001
名媛妹妹
名媛妹妹 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:40

    There's no way to know what all the relations are without specifying them yourself. How the other answers posted are good, but I wanted to add a few things.

    Base Model

    I kind of have the feeling that you want to do this in multiple models, so at first I'd create a BaseModel if you haven't already.

    class BaseModel extends Eloquent {
        public $allRelations = array();
    }
    

    "Config" array

    Instead of hard coding the relationships into a method I suggest you use a member variable. As you can see above I already added $allRelations. Be aware that you can't name it $relations since Laravel already uses that internally.

    Override with()

    Since you wanted with(*) you can do that too. Add this to the BaseModel

    public static function with($relations){
        $instance = new static;
        if($relations == '*'){
            $relations = $instance->allRelations;
        }
        else if(is_string($relations)){
            $relations = func_get_args();
        }
        return $instance->newQuery()->with($relations);
    }
    

    (By the way, some parts of this function come from the original Model class)

    Usage

    class MyModel extends BaseModel {
        public $allRelations = array('foo', 'bar');
    }
    
    MyModel::with('*')->get();
    

提交回复
热议问题