簡體   English   中英

按 id 分組 Laravel Eloquent pivot 值

[英]Group Laravel Eloquent pivot values by id

我有一個關系數據庫,其模型如下所示:
餐廳:

class Restaurant extends Authenticatable
{
    public function dishes()
    {
        // return $this->hasMany(Dish::class);
        return $this->belongsToMany('App\Models\Dish');
    }
}

盤子:

class Dish extends Model
{
    public function orders()
    {
        return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
    }

    public function restaurant()
    {
        return $this->belongsToMany('App\Models\Restaurant');
    }
}

命令

class Order extends Model
{
    public function dishes()
    {
        return $this->belongsToMany('App\Models\Dish');
    }
}

我正在按 id 檢索屬於餐廳的所有訂單,如下所示:

public function index($id)
    {
        $user_id = $id;
        $dishes = Dish::where('restaurant_id', $user_id)->get();

        foreach ($dishes as $dish => $value) {
            $orders = $value->orders;
            foreach ($orders as $order => $value) {
                $response[] = $value;
            }
        }
        return response()->json($response);
    }

這可行,但我想以某種方式按 order_id 對這些結果進行分組,以便返回類似於以下內容的內容:

 {
        "id": 28,
        "status": 1,
        "address": "Fish Street",
        "user_name": "Artyom",
        "user_surname": "Pyotrovich",
        "phone": "351 351 643 52",
        "email": "artyom@restaurant.com",
        "total": 35.8,
        "created_at": "2021-11-17T10:44:58.000000Z",
        "updated_at": "2021-11-17T10:44:58.000000Z",
        "dishes": [{
            "dish_id": 22,
            "quantity": 3
                   }, 
                   {
            "dish_id": 23,
            "quantity": 1
                  }]
    }

這是否可以通過簡單地更改 Eloquent 查詢來實現,或者我是否需要對當前查詢的結果執行多個操作? 還對這些情況下的最佳實踐感興趣。 提前致謝

您可以使用::with()方法來獲取所有所需的關系,這比 foreach 重寫要干凈得多。

例子:

$orders = Order::with('dishes')
    ->whereHas('dishes', function(Builder $dishes) use ($user_id) {
        $dishes->where('restaurant_id', $user_id);
    })->get();

return response()->json( $order );

小記:

把用戶id和餐廳id分開,如果用戶有多家餐館怎么辦?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM