dpbz14739 2018-10-15 10:39
浏览 53

我想在高级连接子句中使用多个表

I need some help on my query. I use multiple tables with advanced join clauses but it shows invalid count and both has same value:

$parents = DB::table('users')
            ->select('users.id','users.full_name', 'users.email', 'users.avatar', 'users.signup_date', (DB::raw('count(children.id) as children_no')), (DB::raw('count(invitations.id) as invitations_no')))
            ->leftJoin('children', function ($join) {
                $join->on('users.id', '=', 'children.userid')
                ->where('children.is_deleted', '=', 0);
            })
            ->leftJoin('invitations', function ($join) {
                $join->on('users.id', '=', 'invitations.user_id')
                ->where('invitations.is_deleted', '=', 0);
            })
            ->where('users.is_admin', '=', 0)
            ->groupBy('users.id')
            ->get();
  • 写回答

1条回答 默认 最新

  • duanjitong7226 2018-10-15 10:56
    关注

    I think you can solve this problem with basic relationships in Laravel + soft deletes on the invitations and children table.

    This will make your query less complex and you have the Laravel benefits.

    <?php
    
    $users = User::where('is_admin', false)
        ->has(['invitations', 'children'])
        ->withCount(['invitations', 'children'])
        ->get();
    

    This wil select all none admins, with invitations and children. Make sure you have soft deletes setup on children and invitations. The withCount will add a count for the related relations.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题