简体   繁体   English

Laravel渴望在其他表上加入join

[英]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? 我可以将此代码更改为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 User: 班级用户:

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

You should just have a Locations model which will have a relationship with Book model, and call it like this: 您应该只具有一个与Book模型有关系的Locations模型,并这样称呼它:

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

This will give you the users with books and location of each book. 这将为您提供用户书籍和每本书的位置。

I think you can try this: 我认为您可以尝试以下方法:

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();

Hope this help you! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM