所以我正在使用 querybuilder 构建一个查询,在该查询中,我需要计算一个连接表中的行,该连接表具有来自另一个表的 where 条件。我最终无法加入该表,因为它会导致将错误的行与此特定联接进行比较。我认为高级连接子句将允许在它自己的范围内添加另一个连接,但情况似乎并非如此。
这是我尝试过的:
$profile = DB::table('users')
->select('users.username', 'users.profile_picture', 'users.screen_state',
'count(replies.id) as replies', 'count(interactions.id) as interactions',
'count(alerts.id) as alerts', 'count(user__followers.id) as followers',
'count(user__following.id) as following', 'count(following.id) as volgend')
->leftJoin('replies', function($join)
{
$join->on('users.id', '=', 'replies.user_id')
->leftJoin('alerts')
->on('replies.alert_id', '=', 'alerts.id')
->where('replies.user_id', '=', $user->id)
->where('alerts.hide', '=', 0);
})
->leftJoin('interactions', function($join)
{
$join->on('users.id', '=', 'interactions.user_id')
->leftJoin('alerts')
->on('interactions.alert_id', '=', 'alerts.id')
->where('interactions.user_id', '=', $user->id)
->where('alerts.hide', '=', 0);
})
->leftJoin('alerts', function($join)
{
$join->on('users.id', '=', 'alerts.user_id')
->where('alerts.user_id', '=', $user->id)
->where('alerts.hide', '=', 0);
})
->leftJoin('user__followers as user__following', function($join)
{
$join->on('users.id', '=', 'user__followers.user_id')
->where('user__followers.user_id', '=', $user->id)
->where('user__followers.follower_id', '=', $searchid);
})
->leftJoin('user__followers as following', function($join)
{
$join->on('users.id', '=', 'user__followers.user_id')
->where('user__followers.user_id', '=', $user->id);
})
->leftJoin('user__followers', function($join)
{
$join->on('users.id', '=', 'user__followers.user_id')
->where('user__followers.follower_id', '=', $user->id);
})
->where('users.id', '=', $user->id)
->get();
我在原始 sql 中也有这个查询,所以你可以看到我想要实现的目标:
SELECT u.username, u.profile_picture, u.screen_state,
(SELECT count(DISTINCT r.id)
FROM `reply` r
LEFT JOIN alerts a
ON r.alert_id = a.alert_content_id
WHERE r.user_id = :userid AND a.hide=0)
AS replies,
(SELECT count(DISTINCT i.id)
FROM `interactions` i
LEFT JOIN alerts a
ON i.alert_id = a.alert_content_id
WHERE i.user_id = :userid AND a.hide=0)
AS interactions,
(SELECT count(DISTINCT a.alerts)
FROM `alerts` a
WHERE a.user_id = :userid AND a.hide=0)
AS alerts,
(SELECT count(DISTINCT uf.id)
FROM `user_followers` uf
WHERE uf.user_id = :userid
AND uf.follower_id = :searchid)
AS following,
(SELECT count(DISTINCT uf.id)
FROM `user_followers` uf
WHERE uf.user_id = :userid)
AS volgend,
(SELECT count(DISTINCT uf.id)
FROM `user_followers` uf
WHERE uf.follower_id = :userid)
AS followers
FROM users u
WHERE id = :userid GROUP BY id
但这给了我一个错误:
Call to undefined method Illuminate\Database\Query\JoinClause::leftJoin()
所以我的问题是如何加入一个表并检查另一个表中的条件?