Reputation: 1989
I have a belongsToMany relation of user and resource.
User:
public function resources() {
return $this->belongsToMany('Resource')->withPivot(array('value'));
}
Resource:
public function users() {
return $this->belongsToMany('User')->withPivot(array('value'));
}
the intermediate table is resource_user
.
With:
$resources = Sentry::getUser()->resources()->get();
I get all the resources where the user_id is in the resource_user table. so far so good. But how can I get ALL the resources entries, even the user_id is not present at the intermediate table? Let's say I have 3 resources in the resource Table. Id 1, 2 and 3. I have one user with ID 1. In the intermediate Table I have ONLY 2 rows:
resource_id 1 and user_id 1 and value 50.
resource_id 2 and user_id 1 and value 100.
But I want display ALL the resources, and if the user is not present there, there should be resource object but without the relation model of the user.
whereHas
isn't working with this problem.
so my goal is to get 3 results, and not 2. something like this:
resource_id 1 user_id 1 value 50
resource_id 2 user_id 1 value 100
resource_id 3 user_id 0 value 0
The only thing what I figured out is this:
In the resource model I create a function like this:
# 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;
}
}
But I wonder there exist an cleaner eloquent way for this? Any Idea of that?
Upvotes: 0
Views: 2362
Reputation: 152880
I'm not sure if I understood you quite right but to get "all resources" you can just use the Resource
model:
$resources = Resource::with('users')->get();
To only eager load the current user you can add a filtering closure:
$resources = Resource::with(array('users' => function($q) use ($userId){
$q->where('user_id', $userId);
}))->get();
Upvotes: 2