Where NOT in pivot table

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

In Laravel we can setup relationships like so:

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


        
7条回答
  •  旧时难觅i
    2020-12-13 19:27

    Ended up writing a scope for this like so:

    public function scopeAvail($query)
    {
        return $query->join('item_user', 'items.id', '<>', 'item_user.item_id')->where('item_user.user_id', Auth::user()->id);
    }
    

    And then call:

    Items::avail()->get();
    

    Works for now, but a bit messy. Would like to see something with a keyword like not:

    Auth::user()->itemsNot();
    

    Basically Eloquent is running the above query anyway, except with a = instead of a <>.

提交回复
热议问题