简体   繁体   中英

Retrieve data from multiple related table in laravel

I have 3 related models. 1.User

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

2.Book

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

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

3.Books_photo

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

The relations are

User hasmany Book

and

Book hasmany Books_photo

So I want to get all the books with their photo of a particular user.

I can get all the books of a user.I'm using this approach

$User = User::with('book')->find(decrypt($request->id));

But this returns only the data in book and user table. How can i fetch the photos too.

You're looking for nested eager loading . You will want to do this:

$User = User::with('book', 'book.photo')->find(decrypt($request->id));

The book.photo is a nested eager load that will tell eloquent to get the photo relation from the book model.

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