laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.38k stars 10.97k forks source link

`->getQuery()` on a many to many returns a mixed (incorrect) result set #48395

Closed ebebbington closed 1 year ago

ebebbington commented 1 year ago

Laravel Version

10.0

PHP Version

8.2.7

Database Driver & Version

MYSQL 8.0.31 for Linux AMD64

Description

There seems to be an issue with ->getQuery() when used on a belongs to many relationship, where the SQL itself and result set actually returns incorrect data. For example take say I have ->belongsToMany(User:class), calling ->getQuery()->get() returns a collection of User models, but the id is that of the pivot, alongside the fields being a complete mix of both the pivot table and users table

Steps To Reproduce

  1. Have a generic table, in this example it is organisations. Assume this table has a organisation_name field
  2. Have another generic table, in this example it is users. Assume this table has a username field
  3. Have a pivot table, in this example it is organisation_user, which has a foreign key for organisation_id and user_id
  4. Create the relation in your Organisation model:
    public function users(): BelongsToMany
    {
    return $this->belongsToMany(User::class);
    }
  5. Create an organisation (organisations table):
    id       organisation_name
    1         org name
  6. Create a user (users table)
    id        username
    2         user name

    (It's key that the id in all tables are different)

  7. Create a pivot (organisation_user table)
    id     organisation_id    user_id   pivot_field
    3      1                      2        some data
  8. Echo results
    $query = Organisation::find(1)->users()->getQuery();
    dd($query->toSql(), $query->get());

You will notice that the id of each model is actually the id of the pivot, and not from the users table, it then combines the fields so it may look like:

Collection {
  User {
    id => 3 // This is the id of the pivot, it should be the id from `users`
   username => 'user name'
   pivot_field => 'some data'
  }
}

As you can see, the model is User, but the id is from a different table, and contains fields from both the users and pivot table

driesvints commented 1 year ago

Hey there,

Can you first please try one of the support channels below? If you can actually identify this as a bug, feel free to open up a new issue with a link to the original one and we'll gladly help you out.

Thanks!