【问题标题】:Laravel eager loading with join on other tableLaravel 急切加载并在其他表上加入
【发布时间】:2017-11-27 04:32:19
【问题描述】:

我可以将此代码更改为 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()

班级用户:

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

【问题讨论】:

    标签: php laravel laravel-5 inner-join eager-loading


    【解决方案1】:

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

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

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

    【讨论】:

    • 类书扩展模型 { 公共功能位置() { 返回 $this->hasOne(Location::class); } } 但错误:“where 子句”中的未知列“locations.book_id”(SQL:select * from locations where locations.book_id in (1))
    【解决方案2】:

    我想你可以试试这个:

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

    希望对您有所帮助!

    【讨论】:

    • 哎呀!我想使用急切加载
    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 2014-08-13
    • 2021-04-23
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多