简体   繁体   中英

Laravel eloquent model - get rows using intermediate table

I have 3 tables users, posts and photos.

post table has one - one relation to photos & users like, post.user_id=users.id and post_photo_id=photos._id .

I use

public function posts(){
    return $this->hasMany('Post');
}

and I get all the posts by user using $user->posts().

What I need is to get all the photos by user, something like $user->photos.

SELECT photos.* FROM photos JOIN posts ON posts.photo_id=photos.id JOIN users ON users.id=posts.user_id WHERE user_id=1

Note: photos table has just 2 fields, id & photo.

In your User model, create a relationship like

Class User Extends Model
{
...
public function photos()
{
   return $this->hasManyThrough('Photos','Posts','photo_id','id');
   // Params (all strings): Final Model, Intermediate Model, Intermediate Model Key (posts), final Model Key (your photos)  
}

public function Posts()
{
   return $this->hasMany('Posts');
}
...
}// end class

Then in your controller, you'll just call your data with the relationships. This assumes you're hinting, but you get the idea...

$picturesByUser = $this->user->with(['posts','photos'])->find($id);

finally, in your blade, just eager load them...

@foreach(...)
  $user->photos->pathToPicture;
  $user->posts->pictureTitle;
@endforeach

Straight out of the Laravel Docs

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