简体   繁体   中英

Eager loading: How to get a few photos from table with polymorph relationship

I wont to get a list of users with avatar and 4 photos like as on screenshot: 在此处输入图片说明

User model:

   public function avatar()
   {
      return $this->morphOne(Photo::class, 'photoable')
        ->where('photoable_type', 'user');
   }

   public function photos()
   {
     return $this->morphMany(Photo::class, 'photoable')
        ->where('photoable_type', 'photo');
   }

   public function scopeLastPhotos($query)
   {
      return $query->with(['photos' => function ($query) {

         $query->take(4)->get();

      }]);
   }

Photo model:

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

I tried:

$users = User::with('avatar')->lastPhotos()->get();

but result had only avatar and empty photos collection:

在此处输入图片说明

All photos are exists on table.

I resolved this issue with mysql function 'group_concat':

public function scopeLastPhotos($query)
{
   return $query->join('photos', 'photos.photoable_id', 'users.id')
        ->selectRaw('users.*, group_concat(photos.hash) as hashes')
        ->where('photos.photoable_type', 'photo')
        ->groupBy('photos.photoable_id');
}

But 'group_concat' doesn't have 'limit' https://bugs.mysql.com/bug.php?id=30098 .

For my task I used this decision:

@foreach(explode(',', $user->hashes) as $hash)

    {{ $hash }}

    @break($loop->iteration == 4)

@endforeach

But maybe somebody know more elegant resolve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM