php - Laravel 4 查询生成器 - 具有复杂的左连接

标签 php mysql sql laravel-4 laravel-query-builder

我是 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();

最佳答案

我相信这应该有效:

$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();

关于php - Laravel 4 查询生成器 - 具有复杂的左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773790/

相关文章:

php - 将 MySQL 插入从逗号分隔转换为管道

PHP 和 file_exists - 澄清文档注释

php - 一个统一的 SQL 查询来处理不同的选择选项值

mysql - 对于弱实体和它所依赖的强实体之间的关系我们能说什么呢?

mysql - 为用户帐户编写系统

sql - oracle中<number>d或<number>f是什么意思?

php - 使用带有未知数量参数的bind_parameters

php - 回滚特定迁移?

python - 如何使用 Python 处理 SQL 转储

SQL 触发器 - 基础知识帮助