Laravel eloquent 中的多个左连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37400912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:51:14  来源:igfitidea点击:

Multiple left joins in laravel eloquent

phpmysqlsqllaraveleloquent

提问by Sebastian

I am trying to understand left joining in eloquent, but I really cant get it to work.

我试图理解 left 加入 eloquent,但我真的无法让它发挥作用。

My regular SQL looks as following:

我的常规 SQL 如下所示:

SELECT uploads.id, comments.file_id, comments.comment, users.id, comments.user, users.name
FROM uploads
LEFT JOIN comments
ON uploads.id=comments.file_id
LEFT JOIN users
ON users.id=comments.user;

Can someone please help me to convert this to a working eloquent query? And maybe provide some info how its done?

有人可以帮我将其转换为有效的雄辩查询吗?也许提供一些信息它是如何完成的?

Thank you! :D

谢谢!:D

回答by Felippe Duarte

Eloquent doesn't perform SQL join, but simulate it with a lot of queries.

Eloquent 不执行 SQL 连接,而是用大量查询来模拟它。

You will get what you want doing this:

你会得到你想要的:

Uploads::with('commments','users')
    ->get(['id','comments.file_id',' comments.comment', 'users.id', 'comments.user', 'users.name']);

Using this, you need to explict have the relations in your models. Check the docs.

使用它,您需要在模型中明确具有关系。检查文档。

Another way is with Query Builder. You are NOT using Eloquent doing this, but will work, of course:

另一种方法是使用查询生成器。你没有使用 Eloquent 来做这件事,但当然可以工作:

DB::table('uploads')
    ->select('uploads.id','comments.file_id',' comments.comment', 'users.id', 'comments.user', 'users.name')
    ->leftJoin('comments','uploads.id','=','comments.file_id')
    ->leftJoin('users','users.id','=','comments.user')
    ->get();

回答by Sebastian

$comments = DB::table('comments')
                ->leftJoin('users', 'users.id', '=', 'comments.id')
                ->leftJoin('uploads', 'uploads.id', '=', 'comments.file_id')
                ->get();

This was the answer, got it working, thanks anyway!

这就是答案,让它工作,无论如何谢谢!