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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?