代码之家  ›  专栏  ›  技术社区  ›  Bruno Francisco

如何使用laravel雄辩子查询获得结果

  •  0
  • Bruno Francisco  · 技术社区  · 7 年前

    我一直在尝试使用子查询来获得结果。我需要执行两个子查询,但到目前为止还不能得到结果。

    以下查询生成所需的结果:

    SELECT x.responsible_cook_id, x.d
    FROM (
        SELECT 
            responsible_cook_id, 
            count(*) d
        FROM orders 
        GROUP BY responsible_cook_id
        ORDER BY count(*)  ASC
    ) as x
    WHERE x.responsible_cook_id IN (
        SELECT ID
        FROM users
        WHERE type = "cook" AND shift_active = 1
    )
    ORDER BY x.d;
    

    到目前为止,我已经尝试使用这种方法通过雄辩的方式执行相同的查询:

    $fSubquery = Order::select('responsible_cook_id, count(*) as d')->groupBy('responsible_cook_id')->orderByRaw('count(*) ASC');
            $sSubquery = User::where('type', 'cook')->where('shift_active', 1);
    
            $users = DB::table(DB::raw("({$fSubquery->toSql()}) as x"))
                ->mergeBindings($fSubquery->getQuery())
                ->whereRaw("x.responsible_cook_id IN {$sSubquery->toSql()}")
                ->mergeBindings($sSubquery->getQuery())
                ->select('x.responsible_cook_id, x.d')
                ->orderByRaw('ORDER BY x.d')->get();
    

    最后一个查询没有返回任何结果。有没有办法执行这些子查询并得到结果?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Bruno Francisco    7 年前

    好吧,我不能解决上面的问题,但这只是一个学习的一部分,有时当你放手它只是碰巧自己解决,有时甚至帮助你。

    我没有执行3个查询(2个子查询+outter查询),而是使用laravel的雄辩的

    事情是这样的

     // Get all cookers that have an active shift
     $cookersWorking = User::where('type', 'cook')
       ->where('shift_active', 1)
       ->select('id')
       ->get();
    

    在得到所有轮班的炊具后,我得到了所有的炊具,这些炊具的菜肴数量最少:

    // We will get the cooker that has the least orders to prepare
    $cookerWithLessDishes = Order::select('responsible_cook_id', DB::raw('count(*) as d'))
        ->whereNull('end') // added this but is not in the original question
        ->whereIn('responsible_cook_id', $cookersWorking->pluck('id'))
        ->groupBy('responsible_cook_id')
        ->orderByRaw('count(*) ASC')
        ->first();
    

    我想我可以把这个问题简化为两个问题。如果我错了,请纠正我。

    快乐编码