首页 文章

laravel belongsToMany包含所有模型行

提问于
浏览
0

我有一个belongsToMany用户和资源的关系 .

User:

public function resources() {
        return $this->belongsToMany('Resource')->withPivot(array('value'));
    }

Resource:

public function users() {
        return $this->belongsToMany('User')->withPivot(array('value'));
    }

中间表是 resource_user . 附:

$resources = Sentry::getUser()->resources()->get();

我获得了user_id在resource_user表中的所有资源 . 到现在为止还挺好 . 但是,如何获取所有资源条目,即使user_id不在中间表中?假设我在资源表中有3个资源 . Id 1,2和3.我有一个ID为1的用户 . 在中间表中,我只有2行:

resource_id 1和user_id 1和值50. resource_id 2和user_id 1和值100 .

但我想显示所有资源,如果用户不在那里,应该有资源对象但没有用户的关系模型 .

whereHas 无法解决此问题 .

所以我的目标是得到3个结果,而不是2.这样的东西:

resource_id 1 user_id 1 value 50 resource_id 2 user_id 1 value 100 resource_id 3 user_id 0 value 0

我想到的唯一的事情就是:

在资源模型中,我创建了一个这样的函数:

# Get specific User value from resource
    public function userValue() {
        $res_user = DB::table('resource_user')->whereUserId(Sentry::getUser()->id)->whereResourceId($this->id)->first();
    if($res_user){
        return $res_user->value;
    }else{
        return 0;
    }
}

但我想知道这有一种更清晰的雄辩方式吗?有什么想法吗?

1 回答

  • 2

    我不确定我是否理解你是对的,但是为了获得"all resources"你可以使用 Resource 模型:

    $resources = Resource::with('users')->get();
    

    要只加载当前用户,您可以添加过滤关闭:

    $resources = Resource::with(array('users' => function($q) use ($userId){
        $q->where('user_id', $userId);
    }))->get();
    

相关问题