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.

reslut

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

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -