vendredi 11 décembre 2015

Laravel 5 eager loading with variable model

I am trying to eager load a relation that is defined by a variable classname. Here is what this looks like:

class Dashboard extends Model {
    public function modules(){
        return $this->belongsToMany('App\Module');
    }
}

class Module extends Model {
    public function model(){
        return $this->hasOne($this->model_class);
    }
}

So the "model" attribute is a model of class $this->model_class

When I have a Module object and call

$this->model

I get the expected result. But when I try to do

$dashboard->modules()->with('model')->get()

I get this error: 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class name must be a valid object or a string'. I assume this is happening because before the Module class is instantiated, there is no model_class attribute and therefore it cannot eager load the model. How can I use eager loading in this situation? Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire