framework: [5.3.26] BelongsToMany withCount selects incorrect id.

  • Laravel Version: 5.3.26
  • PHP Version: 7.0.13
  • Database Driver & Version: MariaDB-10.1.19

Description:

With a belongsToMany => belongsToMany, using the Builder::withCount() causes the incorrect id to be selected, it appears the id from the pivot table is being selected rather than the table itself.

Here are the models:

  • User (users)
class User extends Model {
   ...
   public function roles() {
      return $this->belongsToMany(Role::class);
   }
   ...
}

users

id name email
9 Some Name name@example.com
  • Role (roles)(role_user)(permission_role)
class Role extends Model {
   ...
   public function permissions() {
      return $this->belongsToMany(Permission::class);
   }
   ...
}

roles

id name description
2 Administrator Some description here

role_user

id role_id user_id
4 2 9

permission_role

id permission_id role_id
12 19 2
13 20 2
14 17 2
15 21 2
  • Permission (permissions)
class Permission extends Model {
   ...
}

Steps To Reproduce:

  1. Grab the roles for the user with the permission count.
$roles = $user->roles()->withCount('permissions')->get()
  1. Check the first role id.
$role_id = $roles->first()->id;
  1. The givenid is 4 (from the role_user table), when it should be 2 (from the roles table).
array(
   "id" => 4, // this should be 2.
   "name" => "Administrator",
   "description" => "Some description here",
   "role_id" => 2,
   "user_id" => 9,
   "permissions_count" => 4,
)

Additionally: the role_id and the user_id should be in a pivot key.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 17 (13 by maintainers)

Most upvoted comments

@cabalopolis

I can reproduce it too, with your repo… 😸

reproduce

Reproduced with sqlite…

I haven’t tested but it but I wouldn’t expect it to work because these are the default values for belongsToMany relationship.