Jan 8, 2019
0
Level 2
Eloquent belongsToMany query help
Hey everyone, I'm trying to specify a belongsToMany relationship with a setup where with :
Content -> Licenses -> Orgs
So say a simpler approach in my Content model I have these two relationships:
public function licenses_public() {
return $this->belongsToMany(License::class)
->whereDoesntHave('orgs');
}
and
public function licenses_private() {
return $this->belongsToMany(License::class)
->whereHas('orgs', function($query) {
$query->where('org_id', Auth::user()->org_id);
});
}
Now I'd like to have a relationship that is a combination of these two, and does essentially this:
public function getLicensesFilteredAttribute() {
if ($this->licenses_private->count()) {
return $this->licenses_private;
}
return $this->licenses;
}
If ANY licenses have an org that is of the logged in users org_id, ONLY return those, otherwise return all licenses not bound to any orgs.
Is this possible at all at the query level? as a relationship??
Please or to participate in this conversation.