哪里不在枢轴表 [英] Where NOT in pivot table

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

问题描述

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

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

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

然而,如果我想得到相反的话,该怎么办?并获取用户所没有的所有项目。所以不在数据透视表中。



有没有一个简单的方法呢?

解决方案

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

  //用户模型
public function availableItems()
{
$ ids = \DB :: table('item_user') - > where('user_id','=',$ this-> id ) - >列表( 'USER_ID');
return \Item :: whereNotIn('id',$ id) - > get();
}

使用电话:

 验证::用户() - > availableItems(); 


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?

解决方案

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();
}

To use call:

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

这篇关于哪里不在枢轴表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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