我有一个简单的查询,我应该以雄辩的方式运行,如下所示
SELECT `followers`.*, `fol`.`followed_id` AS `is_fan`
FROM `followers`
LEFT JOIN `followers` AS `fol` ON `fol`.`follower_id` = `followers`.`followed_id`
AND fol.followed_id = ?
WHERE `followers`.`followed_type` = ?
AND `followers`.`followed_id` = ?
GROUP BY `followers`.`followed_id`, `fol`.`followed_id`
ORDER BY `created_at` DESC
然后我用eloquent做了一个正确的查询:
$this->follow->with('follower')
->where('followers.followed_type', $followed['follower_type'])
->where('followers.followed_id',$followed['follower_id'])
->leftJoin('followers as fol',function($join) use ($followed)
{
$join->on('fol.follower_id','=','followers.followed_id')
->where('fol.followed_id','=','followers.follower_id');
})
->groupBy('followers.followed_id')
->groupBy('fol.followed_id')
->select('followers.*',"fol.followed_id as is_fan")
->get();
经过大量的调试以了解为什么列is_fan
没有被填充为例外,我试图对where
上传递的值进行硬编码在连接闭包中查看响应像这样:
->leftJoin('followers as fol',function($join) use ($followed)
{
$join->on('fol.follower_id','=','followers.followed_id')
->where('fol.followed_id','=',1);
})
它已经工作了,所以我得到的解决方案是第三个参数不能是这个案例followers
中父表的参数。有没有可能获得父表e的值作为where
闭包中LeftJoin
方法中的第三个参数传递?
答案 0 :(得分:1)
您的代码唯一的问题是,where
使用参数绑定,因此'followers.follower_id'
在此处理为字符串:
->where('fol.followed_id','=','followers.follower_id');
DB::raw()
在这里还不够,因为JoinClause
s where
的工作有点偏差,显然你只需要另一个on
:
->on('fol.followed_id','=','followers.follower_id');