Udev's avatar
Level 2

get first item in relationship

I have a one to many relation. I am trying to get all the parent models with only the first child. I have tried :

A::with(['B' => function($q) {
		$q->first()
}])->all()

However, this results in the first of A having 1 of B and the rest of A don't have a relation B value.

0 likes
3 replies
Udev's avatar
Level 2

@webrobert Thanks for this. How could this work for a one to many polymorphic? My actual situation is that I have a one to many polymorphic relation. Post model and Product model have a one to many polymorphic relation to Files model.

//Files Model
public function fileable()
{
      return $this->morphTo();
}

//Post Model
public function files()
{
      return $this->morphMany(File::class, 'fileable');
}

//Product Model
public function files()
{
        return $this->morphMany(File::class, 'fileable');
}

I'm trying to increase performance by limiting to only the first file(cover photo) on a page listing all post/products. I'm trying to avoid adding a cover_photo field in each Post and Product model.

MohamedTammam's avatar
Level 51

Create another relationship

//Product Model
public function files()
{
        return $this->morphMany(File::class, 'fileable');
}

public function file()
{
        return $this->morphOne(File::class, 'fileable');
}

Then use that file relationship if you want to get the first one

1 like

Please or to participate in this conversation.