dimanche 27 août 2017

Laravel 5.4 - Return single row from joined table

I have model Album (table albums) and model Photo (table photos). When I'm fetching all albums to page, I would like to display first photo from each album as album image.

Album model:

public function photos()
{
    return $this->hasMany('App\Photo');
}

Photo model:

public function album()
{
    return $this->belongsTo('App\Album');
}

Query:

public function getAlbums()
{
   return DB::table('albums')
        ->join('photos', 'albums.id', '=', 'photos.album_id')
        ->select('photos.title', 'albums.title AS album_title', 'albums.slug AS album_slug')
        ->get();
}

It returns all photos with album title. How to modify the query to return only first photo from each album? How to use LIMIT 1 in joined table? Or is there another way to do this? Thanx.

Reslut



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

Aucun commentaire:

Enregistrer un commentaire