mardi 7 mai 2019

Laravel - how get a single model instance not as collection, but single model from belongsToMany

I have this relation defined in one of my models. It is the simplest possible case.

public function entities()
{
    return $this->belongsToMany(\App\Models\Entity::class, 'entity_related', 'related_id', 'entity_id');
}

Now, I want to create a relation which gets only one model from the table.

Current solution:

I just defined the same relation, but with ->take(1). Crude, but it works. The downturn of this solution is that I need to do a foreach loop to get my desired single model.

public function firstOfEntities()
{

    return $this->belongsToMany(\App\Models\Entity::class, 'entity_related', 'related_id', 'entity_id')->take(1);
}

TO DO

how to properly define a relation which gets only one (just any) model instance, instead of creatng a collection?

Thank you in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire