简体   繁体   中英

Laravel Eloquent multiple method chaining

I have a project with laravel that i have some tables like below:

#users table:
->id
->username
->password

#profile table:
->id
->user_id
->firstname
->lastname

#articles table:
->id
->user_id
->title
->body

#photos table:
->id
->article_id
->path

to getting user articles photo i'm wondering what should i do with eloquent i set the relationships in model but when i first just tried it i noticed i cant just do something like

User::find(1)->articles()->photos();

then i tried some other ways but i failed!
and now i want to know how can i retrieve the photos related to the user and its article?
thank you guys in advance.

You can use the with method to eager load the relationships. You can also use the dot notation to eager load "nested" relationships.

Example:

User::with('articles.photos')->find(1);

This will retrieve the user with a primary key of 1. It will also retrieve all of the user's articles and the photos related to those articles.

Docs on eager loading and the dot notation: http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

You'll have to pluck the photos out of the articles collection:

$user = User::with('articles.photos')->find(1);

$photos = $user->articles->pluck('photos')->collapse();

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