Skip to content

updateExistingPivot or save on a pivot model updates all entries with the same related and foreign id's #56399

@johannessmit

Description

@johannessmit

Laravel Version

12.20.0

PHP Version

8.3.21

Database Driver & Version

No response

Description

Bug description:

When using pivot tables with a pivot model, when using updateExistingPivot, it updates all pivots with the related and foreign id's, even if other filters on pivot table columns are applied.

I haven't had the time to figure everything out, but it seems it has to do something with the changes in the following line:

12.x:
https://github.com/laravel/framework/blob/12.x/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php#L214

11.x:
https://github.com/laravel/framework/blob/11.x/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php#L210

Work-around:

Make sure pivot tables where an identical foreign and related combination is possible since another pivot table column is added to the primary key, are updated so they have a primary auto-incrementing key, this fixes the problem since the AsPivot::setKeysForSaveQuery then uses the primary key instead of the foreignKey / relatedKey combination.

Related:

#55720
#55428
#55280
#55490

Steps To Reproduce

Since the code-base this is happening is closed, I cannot share the exact table's.

But an easy reproducible situation:

  • create a role table
  • create a team table
  • create a user_has_roles table
    • This has two extra pivot columns: team_id and last_used (timestamp)

Create a simple controller that makes it possible to switch between teams, where an user can have the same role_id for multiple teams in the pivot table.

I am happy to provide a working example later today, let me know if desired.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions