Where NOT in pivot table

前端 未结 7 1734
栀梦
栀梦 2020-12-13 19:02

In Laravel we can setup relationships like so:

class User {
    public function items()
    {
        return $this->belongsToMany(\'Item\');
    }
}
         


        
7条回答
  •  失恋的感觉
    2020-12-13 19:23

    It's not that simple but usually the most efficient way is to use a subquery.

    $items = Item::whereNotIn('id', function ($query) use ($user_id)
        {
            $query->select('item_id')
                ->table('item_user')
                ->where('user_id', '=', $user_id);
        })
        ->get();
    

    If this was something I did often I would add it as a scope method to the Item model.

    class Item extends Eloquent {
    
        public function scopeWhereNotRelatedToUser($query, $user_id)
        {
            $query->whereNotIn('id', function ($query) use ($user_id)
            {
                $query->select('item_id')
                    ->table('item_user')
                    ->where('user_id', '=', $user_id);
            });
        }
    
    }
    

    Then use that later like this.

    $items = Item::whereNotRelatedToUser($user_id)->get();
    

提交回复
热议问题