Laravel Eloquent: eager loading of multiple nested relationships

前端 未结 2 1395
心在旅途
心在旅途 2020-12-13 01:27

What laravel says:

$books = App\\Book::with(\'author.contacts\')->get();

What I need is something like this

$books = App         


        
相关标签:
2条回答
  • 2020-12-13 02:19

    You can do

     $books = App\Book::with('author.contacts','author.publishers')->get();
    
    0 讨论(0)
  • 2020-12-13 02:32

    Laravel documentation on eager loading recommends listing the relationships in an array as follows:

    $books = App\Book::with(['author.contacts', 'author.publishers'])->get();
    

    You can have as many relationships as desired. You can also specify which columns should be included for a relationship like this:

    //only id, name and email will be returned for author
    //id must always be included
    $books = App\Book::with(['author: id, name, email', 'author.contacts', 'author.publishers'])->get();
    

    You may also add constrains as follows:

    $books = App\Book::with(['author: id, name, email', 'author.contacts' => function ($query) {
                                              $query->where('address', 'like', '%city%');
                                         }, 'author.publishers'])->get();
    
    0 讨论(0)
提交回复
热议问题