laravel集合中的groupBy,如果键为null,那么我该怎么办?

问题描述 投票:-1回答:1

我有array个对象,其中某些对象具有cart_tables null,而另一些对象具有cart_tables对象。所以我想要groupBycart_tablescart_id列之类的数据。

查询:

$timeTable = PivotTable::where('times_id', $timeId)
        ->with(['tables'])
        ->with(['orders_tables'])
        ->with(['cart_tables'])
        ->with([
            'cart_tables' => function ($query) {
                $query->whereNotNull('cart_id');
            }
        ])
        ->whereHas('tables', function ($query) use ($restaurantId) {
            $query->where('tables.rest_id', '=', $restaurantId);
        })
        ->get()
        ->groupBy(function ($table, $key) {
            if ($table['cart_tables']) {
                return $table['cart_tables']['cart_id'];
            } else {
                return $table['id'];
            }
        })->values();

这里的问题是,如果false中的条件groupBy然后进入else条件,而在else条件中进入return key "$table['id']"groupBy条件的返回键相同时,则groupBy结果为false

所以,我要对groupBy数据做什么?

提前感谢!

laravel group-by laravel-5.8 laravel-collection
1个回答
0
投票

使用如下所示的查询构建器:-

$timeTable = PivotTable::query();
         $timeTable->where('times_id', $timeId)
        ->with(['tables'])
        ->with(['orders_tables'])
        ->with(['cart_tables'])
        ->with([
            'cart_tables' => function ($query) {
                $query->whereNotNull('cart_id');
            }
        ])
        ->whereHas('tables', function ($query) use ($restaurantId) {
            $query->where('tables.rest_id', '=', $restaurantId);
        });
        if(condition){
           $timeTable->groupBy(..);
            }else{
           $timeTable->groupBy(..);
      }
        $result=$timeTable->values();
© www.soinside.com 2019 - 2024. All rights reserved.