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

时间:2018-11-12 01:26:41

标签: laravel

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

以下查询将产生所需的结果:

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;

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

$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 个答案:

答案 0 :(得分:0)

好吧,我无法解决上面的问题,但这仍然是一种学习,有时候,当您放手时,它会自行解决,有时甚至对您有所帮助。

我没有使用3个查询(2个子查询+外部查询),而是使用Laravel的Eloquent将所有查询减少到一个查询

这是怎么回事

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

我认为我能够将其简化为两个查询。如果我错了,请纠正我。

快乐编码