不在数据透视表中的地方 [英] Where NOT in pivot table

查看:19
本文介绍了不在数据透视表中的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Laravel 中,我们可以像这样设置关系:

In Laravel we can setup relationships like so:

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

允许我们为用户获取数据透视表中的所有项目:

Allowing us to to get all items in a pivot table for a user:

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

但是,如果我想得到相反的结果怎么办.并获取用户尚未拥有的所有项目.所以不在数据透视表中.

However what if I want to get the opposite of that. And get all items the user DOES NOT have yet. So NOT in the pivot table.

有没有简单的方法可以做到这一点?

Is there a simple way to do this?

推荐答案

为了简单和对称,您可以在 User 模型中创建一个新方法:

For simplicity and symmetry you could create a new method in the User model:

// User model
public function availableItems()
{
    $ids = DB::table('item_user')->where('user_id', '=', $this->id)->lists('user_id');
    return Item::whereNotIn('id', $ids)->get();
}

使用通话:

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

这篇关于不在数据透视表中的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆