mardi 3 novembre 2015

Eager load polymorphic relationship straight after creating it

I have a Project model, which hasMany Node models. Node model is morphable:

public function nodeable()
{
   return $this->morphTo();
}

And it can be morphed into Text model or Video model.

Example:

public function node()
{
   return $this->morphOne(Node::class, 'nodeable');
}

It all works perfectly, the one issue I have at the moment is that I need to retrieve a nodeable model straight after creating the Node. For example:

$project = factory(\App\Project::class)->create();
$video = factory(\App\Video::class)->create();
$node = new App\Node;
$project->nodes()->save($node);
$video->node()->save($node);

Now I need to return the newly created Node along with its nodeable relationship model.

One way to do this would be:

return App\Node::with('nodeable')->find($node->id)

which works fine, but as you can see, I'm querying the database, when technically everything I need should already be accessible when creating the model, right?

Is it not possible to just return that nodeable model without having to execute a separate query for it?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire