Skip to content

Fix Role::users() relationship: use belongsToMany for many-to-many - #2

Draft
Blair2004 with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-query-users-by-role
Draft

Fix Role::users() relationship: use belongsToMany for many-to-many#2
Blair2004 with Copilot wants to merge 2 commits into
mainfrom
copilot/fix-query-users-by-role

Conversation

Copilot AI commented Jan 24, 2026

Copy link
Copy Markdown

The Role::users() relationship used hasManyThrough for a many-to-many relationship through the users_roles_relations pivot table. hasManyThrough is designed for indirect relationships (A → B → C), not pivot tables (A ↔ pivot ↔ B).

Changes

src/Models/Role.php

  • Changed users() from hasManyThrough(User, UserRoleRelation, ...) to belongsToMany(User, 'users_roles_relations', 'role_id', 'user_id')
  • Added BelongsToMany return type
  • Added required import

Before/After

// Before
public function users()
{
    return $this->hasManyThrough(
        User::class, UserRoleRelation::class,
        'role_id', 'id', 'id', 'user_id'
    );
}

// After  
public function users(): BelongsToMany
{
    return $this->belongsToMany(
        User::class, 'users_roles_relations',
        'role_id', 'user_id'
    );
}

The generated SQL now correctly joins users through the pivot table. All existing query methods (get(), count(), where(), etc.) remain compatible.

Original prompt

This section details on the original issue you should resolve

<issue_title>Quering Users Through Role instance.</issue_title>
<issue_description>There is a problem with the SQL used for the query that retrieves users using the model Ns\Models\Role (users relationship).

Output:

select * from `users` inner join `users_roles_relations` on `users_roles_relations`.`user_id` = `users`.`id` where `users_roles_relations`.`role_id` = ?"
```</issue_description>

<agent_instructions>Let's evaluate if this error might be accurate.</agent_instructions>

## Comments on the Issue (you are @copilot in this section)

<comments>
</comments>


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Co-authored-by: Blair2004 <5265663+Blair2004@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix SQL query for retrieving users by role Fix Role::users() relationship: use belongsToMany for many-to-many Jan 24, 2026
Copilot AI requested a review from Blair2004 January 24, 2026 23:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quering Users Through Role instance.

2 participants