0

Relation

    public function groups()
    {
            return $this->belongsToMany('App\Models\ItemGroup','item_to_group','item_id','item_group_id');
    }

** How to select all Items that have item_group_id 0 and 9 BOTH?**

    $zero_and_nine_count = \App\Models\Item::with(['groups' => function ($query) {
        $where[] = ['item_group_id', , 0];
        $where[] = ['item_group_id', '=', 9];
        $query->where($where);
    }])->count();

Counts all Items

Working SQL:

SELECT item_id FROM `item_to_group` WHERE `item_group_id` = 9 AND item_id IN (SELECT item_id FROM `item_to_group` WHERE `item_group_id` = 0)
1
  • Subquery Laravel now does have Subquery support so do look into it. Commented Feb 22, 2023 at 10:21

2 Answers 2

0

Reference :

SELECT item_id 
FROM `item_to_group` 
WHERE 
    `item_group_id` = 9 AND 
    item_id IN (
        SELECT item_id 
        FROM `item_to_group` 
        WHERE `item_group_id` = 0
    )

You can query like this :

$items = \App\Models\Item::whereHas('groups', function ($query) {
        $query->where('item_group_id', 9)
            ->whereIn('item_id', function ($subquery) {
                $subquery->select('item_id')
                    ->from('item_to_group')
                    ->where('item_group_id', 0);
            });
    })->get();
1
  • Thx a lot, this solution i had, but i thought that laravel is so smart that there will be more elegant way
    – EgoPrimary
    Commented Feb 22, 2023 at 19:00
0

Sounds like you're looking for whereIn?

$model->groups()->whereIn('item_group_id', [0, 9])->get();
2
  • no, OP is looking for subquery in the eloquent format Commented Feb 22, 2023 at 10:19
  • whereIn is OR logic, i need AND logic
    – EgoPrimary
    Commented Feb 22, 2023 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.