panthro's avatar

Morph One but with Many to Many?

I have a many to many polymorphic relationship.

I am aware of the handy relationship definition of:

$this->morphOne(Image::class, 'imageable')->oldestOfMany();

But thats not for a many to many relationship.

Is there anyway to set this up for a poly many to many where I can get the oldest row?

0 likes
5 replies
kevinbui's avatar

Not a problem, lets look at this classic example from the docs.

What about getting the oldest tag for a video? we can use orderByPivot:

// the sort direction is "asc" by default.
return $video->tags()->orderByPivot('created_at')->first();

Pls let me know if this solves your problem. If you want to define a relationship like oldestImage then we might have to do a bit differently.

panthro's avatar

@kevinbui yes i would like it defined as a relationship, also your example does not just get one item.

kevinbui's avatar

@panthro I have updated my answer accordingly.

As I understand, there’s currently no way to define a one to one relationship out of a polymorphic many to many one.

What problem are you trying to solve here?

panthro's avatar

@kevinbui thank you, I want to define a relationship so I do not have to constrain it on every eager load.

Anyway to define your answer as a relationship and just call that?

kevinbui's avatar

@panthro Nope, as far as I am concerned, you cannot define a relationship that way.

I believe this is what you are doing:

Video::with('tags' => fn ($query) => $query->orderByPivot('created_at')->limit(1))
	->get();

Please or to participate in this conversation.