php - Laravel 5.4 - Return single row from joined table -
i have model album (table albums) , model photo (table photos). when i'm fetching albums page, display first photo each album 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 album_title', 'albums.slug album_slug') ->get(); }
it returns photos album title. how modify query return first photo each album? how use limit 1 in joined table? or there way this? thanx.
why not things laravel way instead of raw db queries? there's trick doing this. first in album model, add method (i use latest()
maybe want oldest()
, or other limit described in docs ):
public function firstphoto() { return $this->hasone('app\photo')->latest(); }
now can do:
public function getalbums() { return albums::with('firstphoto')->get(); }
wiki
Comments
Post a Comment