Laravel Query Builder嵌套连接和别名

时间:2015-08-24 06:33:23

标签: mysql laravel query-builder

如何使用Laravel的查询生成器创建此查询:

SELECT `content`.`tagable_id`,`taged`.`tag_id`
FROM `taged`
RIGHT JOIN
    (SELECT `taged`.`tagable_id`,`taged`.`tag_id`
    FROM `taged`
    WHERE `taged`.`mask_flag`='0'
        AND `taged`.`tagable_type`='App\\\Post'
        AND `taged`.`user_id`='1') AS `content`
ON `taged`.`mask_flag`='1'
    AND `content`.`tagable_id`=`taged`.`tagable_id`
    AND `taged`.`tagable_type`='App\\\Post'
    AND `taged`.`user_id`='1'

内部SELECT taged.tagable_id...周围的括号是我的主要问题所在。

1 个答案:

答案 0 :(得分:1)

这是您的Laravel查询:

$result = DB::table('taged')
             ->select('content.tagable_id', 'taged.tag_id')
             ->rightJoin(DB::raw('SELECT tagable_id, tag_id FROM taged AS content'), function($join)
         {
             $join->on('taged.mask_flag', '=', 1);
             $join->on('content.tagable_id', '=', 'taged.tagable_id');
             $join->on('taged.tagable_type', '=', 'App\\\Post');
             $join->on('taged.user_id', '=', 1);
         })
         ->where('content.mask_flag', '=', 0);
         ->where('content.tagable_type', '=', 'App\\\Post');
         ->where('content.user_id', '=', 1);
         ->get();