Laravel 预先加载并加入其他 table

Laravel eager loading with join on other table

我可以将此代码更改为 has_many 或 has_one 或...的语法以编写漂亮的代码吗?

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

Class 用户:

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

您应该只有一个与 Book 模型有关系的 Locations 模型,并这样调用它:

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

这将为您提供书籍的用户和每本书的位置。

我想你可以试试这个:

DB::table('users')
->select('books.*','locations.name as l_name')
->join('books','users.id','=','books.user_id')
->join('locations','books.id','=','locations.book_id')
->get();

希望对您有所帮助!