我是 Laravel 4 的新手。
我有这个查询:
SELECT a.id, active, name, email, img_location, IFNULL(b.Total, 0) AS LeadTotal, IFNULL(c.Total, 0) AS InventoryTotal
FROM users AS a
LEFT JOIN (
SELECT user_id, count(*) as Total
FROM lead_user
GROUP BY user_id
) AS b ON a.id = b.user_id
LEFT JOIN (
SELECT user_id, count(*) as Total
FROM user_inventory
GROUP BY user_id
) AS c ON a.id = c.user_id
WHERE a.is_deleted = 0
如何将其转换为 Laravel 查询生成器?我对如何在这种类型的查询中使用 Laravel 连接查询生成器感到困惑。
回答!!
将在 laravel 论坛上获得 petkostas 的所有帮助。我们得到了答案。
$users = DB::table('users AS a')
->select(array('a.*', DB::raw('IFNULL(b.Total, 0) AS LeadTotal'), DB::raw('IFNULL(c.Total, 0) AS InventoryTotal') ) )
->leftJoin(DB::raw('(SELECT user_id, COUNT(*) as Total FROM lead_user GROUP BY user_id) AS b'), function( $query ){
$query->on( 'a.id', '=', 'b.user_id' );
})
->leftJoin(DB::raw('(SELECT user_id, COUNT(*) as Total FROM user_inventory WHERE is_deleted = 0 GROUP BY user_id) AS c'), function( $query ){
$query->on( 'a.id', '=', 'c.user_id' );
})
->where('a.is_deleted', '=', 0)
->get();