Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kaos's avatar
Level 2

Group by with 3 joined tables

Hi, I'm working on 3 models: Menu, Inventory, Category

Here the relations:

Menu:


    // Some code here...

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

Inventory:

    public $timestamps = false;

    // Some code here...

    public function category() {
        return $this->belongsTo('App\Models\Category');
    }

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

Category:

    public $timestamps = false;

    // Some code here...

    public function inventories() {
        return $this->hasMany('App\Models\Inventory');
    }

Here the MySql tables: tables

I was able to retrieve all Products of the today Menu ordered by the Category id using this:

    $result = Menu::with([
                'inventories' => function ($query) {
                    $query->with('category')->orderBy('id', 'ASC');
                }
            ])->whereDate('created_at', '=', date('Y-m-d'))
                ->where('shop_id', $this->shop->id)
                ->first(); // The menu it's one per day

I need to retrieve all Categories (not repeated) of the Menu of today ordered by their id, so I should use a GroupBy. This is the wrong attempt:

$result = Menu::with([
            'inventories' => function ($query) {
                $query->with([
                    'category' => function ($category) {
                        $category->select('id', 'name')->groupBy('id', 'name');
                    }
                ])->orderBy('id', 'ASC');
            }
        ])->whereDate('created_at', '=', date('Y-m-d'))
            ->where('shop_id', $this->shop->id)
            ->first(); // The menu it's one per day
0 likes
0 replies

Please or to participate in this conversation.