eloquent-power-joins
eloquent-power-joins copied to clipboard
Left Join Not Working for one relationship but does for another
Hey Guys,
I'm pulling out my hair with this issue since it does not make sense. I hope it's a bug, or something you guys can maybe point me in the direction of what I'm doing wrong.
I have a user's model, with a user's table. I am grabbing a list of users, and then showing them in a table.
I have a sort trait that sorts according to a field name, and 2 of the fields, package_name and owner_username are pulled from other tables, the package name from a packages table (through an alias as below), and the owner_username is pulled from the same users table but just shown as a seperate field so I can sort in mysql directly.
My headache comes with the owner_username, The OwnerUser is also included as a relationship field, and it shows the values of the parent user, but the join does not. It's just empty...
Why would that be? baring in mind the sorting and getting are running in a seperate section so would not be in this part of the code...
$query = User::query() ->with('UserPackage', 'OwnerUser') ->leftjoinRelationship('UserPackage') ->leftjoinRelationshipUsingAlias('OwnerUser', 'owner_alias') ->select('users.*', 'users.role as user_role', 'packages.name', 'packages.name as package_name', 'owner_alias.username as owner_username') ->where(function ($query) { $query->whereBelongsTo(Auth::user(), 'OwnerUser') ->orWhereIn('users.owner', Auth::user()->SubUserIDSArray); }) ->where(function ($query) { $query->where('users.username', 'like', '%' . $this->filters['search'] . '%') ->orWhere('users.email', 'like', '%' . $this->filters['search'] . '%') ->orWherein('users.owner', fn($userquery) => $userquery->select('id')->from('users')->where('username', 'like', '%'.$this->filters['filterOwner'].'%')) ->orWhere('users.role', 'like', '%' . $this->filters['search'] . '%') ->orWhere('packages.name', 'like', '%' . $this->filters['search'] . '%'); }) ->when($this->filters['filterUsername'], fn($query, $username) => $query->where('users.username', 'Like', '%' . $username . '%')) ->when($this->filters['filterOwner'], fn($query, $owner) => $query->wherein('users.owner', fn($userquery) => $userquery->select('id')->from('users')->where('username', 'like', '%'.$this->filters['filterOwner'].'%'))) ->when($this->filters['filterRole'], fn($query, $role) => $query->where('users.role', $role)) ->when($this->filters['filterPackage'], fn($query, $package) => $query->where('packages.name', 'Like', '%' . $package . '%'));