Where NOT in pivot table

前端 未结 7 1742
栀梦
栀梦 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:11

    How about left join?

    Assuming the tables are users, items and item_user find all items not associated with the user 123:

    DB::table('items')->leftJoin(
        'item_user', function ($join) {
            $join->on('items.id', '=', 'item_user.item_id')
                 ->where('item_user.user_id', '=', 123);
        })
        ->whereNull('item_user.item_id')
        ->get();
    

提交回复
热议问题