-
-
Notifications
You must be signed in to change notification settings - Fork 157
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support table aliases with BelongsToMany relationships. #26
Comments
I managed to find a solution by browsing through the old closed issues of this repo. See #15 (comment) . Following it's instructions, I created a pivot class for the Here is my final relationship method: public function organizationsOfUsersWithSharedUserGroups() {
return $this->hasManyDeep(
Organization::class,
[
UsersAndUserGroupsRelationship::class,
UserGroup::class,
UsersAndUserGroupsRelationship::class . ' as alias',
User::class,
'organization_user',
]
);
} Here's the use Illuminate\Database\Eloquent\Relations\Pivot;
use Staudenmeir\EloquentHasManyDeep\HasTableAlias;
class UsersAndUserGroupsRelationship extends Pivot
{
use HasTableAlias;
protected $table = 'user_user_group';
} I'll leave the issue open, in case @staudenmeir might want to update the |
Yes, aliasing a pivot table requires a custom model. I'll add an example to the README. |
@staudenmeir : Thank you! 👍 😃 |
Assume the following entities:
User
UserGroup
Organization
Assume the following relationships:
User
belongs to manyOrganization
s.User
belongs to manyUserGroup
s.Given above, we need a relationship
User::organizationsOfUsersWithSharedUserGroups()
, that would return all theOrganization
s that belongs to any of theUser
s that sharesUserGroup
s with the callingUser
object.PHP has to:
User
object,UserGroup
s,User
s of thoseUserGroup
s (Thus coming back to theUser
class, through the same pivot table.),Organization
s of thoseUser
s.Following relationship definition accomplishes what I am after, with one caveat:
The caveat being
user_user_group2
being a MySQL view defined as follows:Table
user_user_group
and viewuser_user_group2
are identical.If we replace
user_user_group2
withuser_user_group
inUser::organizationsOfUsersWithSharedUserGroups()
's definition, we get the following error:I tried to specify an
as
inUser::organizationsOfUsersWithSharedUserGroups()
's definition as follows, but it did not work.Thus, I would like to propose supporting table aliases with BelongsToMany relationships.
The text was updated successfully, but these errors were encountered: