Search code examples
phplaravellaravel-5inner-joineager-loading

Laravel eager loading with join on other table


can i change this code to syntax of has_many or has_one or ... to write beautiful code?

\App\User::with(['books' => function ($query) {
    $query->join('locations','books.location_id','=','locations.id')
    ->select([
        'books.*',
        'locations.name as l_name'
    ]);
}])->get()

Class User:

public function books()
{
    return $this->hasMany(Book::class);
}

Solution

  • You should just have a Locations model which will have a relationship with Book model, and call it like this:

    User::with('books.locations')->get();
    

    This will give you the users with books and location of each book.