左连接复杂
我是laraval 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();
我相信这应该工作:
$users = DB::table('users')
->select( array('users.*', DB::raw('COUNT(lead_user.user_id) as LeadTotal'), DB::raw('COUNT(user_inventory.user_id) as InventoryTotal') ) )
->leftJoin('lead_user', 'users.id', '=', 'lead_user.user_id')
->leftJoin('user_inventory', 'users.id', '=', 'user_inventory.user_id')
->where('users.is_deleted', '=', 0)
->get();
这种类型的查询非常难以使用查询生成器进行构建。 但是,您可以使用DB::select
如果你没有什么可绑定的,你可以使用以下内容:
DB::select("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");
如果需要将参数与查询绑定:
$deleted = 0;
DB::select("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 = ?", [$deleted]);
链接地址: http://www.djcxy.com/p/18093.html
上一篇: with complicated left joins
下一篇: How to add an additional single column heatmap at the side of main heatmap in R