skip to Main Content

Relation

    public function groups()
    {
            return $this->belongsToMany('AppModelsItemGroup','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 = AppModelsItem::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)

2

Answers


  1. Sounds like you’re looking for whereIn?

    $model->groups()->whereIn('item_group_id', [0, 9])->get();
    
    Login or Signup to reply.
  2. 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 = AppModelsItem::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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search