duanfuxing2212 2018-02-06 23:45
浏览 98
已采纳

如何使用Laravel的查询构建器执行嵌套连接?

Edit: to clarify, I want to get all the Nodes no matter if they have an Image. Further I don't want to return any records from Images_Nodes if there is no corresponding record in Images. This is a simplified version of a more complex query, so don't be cute thinking to tell me that my database isn't designed correctly.


I am using Laravel 5.5 and want to do a slightly more complicated query.

select
    n.Node_id, i.Image_id
from
    Nodes AS n
    left join Nodes_Images AS n_i
        join Images i ON n_i.Image_id = i.Image_id
    ON n.Node_id = n_i.Node_id

I thought that

DB::table('Nodes AS n')
    ->leftJoin('Nodes_Images AS n_i', function ($join) {
        $join->on('n.node_id', '=', 'n_i.node_id')
            ->join('images AS i', 'n_i.image_id', '=', 'i.image_id');
    })->select('n.node_id', 'i.image_id');

would produce it, but it returns

select
    [n].[node_id], [i].[image_id]
from
    [Nodes] as [n] 
    left join [Nodes_Images] as [n_i] 
    on [n].[node_id] = [n_i].[node_id]

and this

DB::table('Nodes AS n')
    ->leftJoin('Nodes_Images AS n_i', 'n.node_id', '=', 'n_i.node_id')
    ->join('images AS i', 'n_i.image_id', '=', 'i.image_id')
    ->select('n.node_id', 'i.image_id');

produces this, which does not nest the Images join inside the outer join

select
    [n].[node_id], [i].[image_id]
from
    [Nodes] as [n]
    left join [Nodes_Images] as [n_i] on [n].[node_id] = [n_i].[node_id] 
    inner join [images] as [i] on [n_i].[image_id] = [i].[image_id]
  • 写回答

1条回答 默认 最新

  • doumang20060820 2018-03-15 03:21
    关注

    This made it into Laravel 5.6.1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。