mercredi 21 juin 2017

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:enter image description here

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:

enter image description here

All photos are exists on table.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2sTy0F3
via IFTTT

Aucun commentaire:

Enregistrer un commentaire