laravel belongsToMany update extra pivot column without any change #45473
Replies: 2 comments 1 reply
-
Beta Was this translation helpful? Give feedback.
-
Just commenting to second this. I feel like this needs to have a pull request assembled once we figure out a good solution. @mderakhshi I believe we're having the same issue, but I'd like to be sure. This is the problem I'm having. If I have this data in my pivot table (connecting a product to categories): category_id product_id type created_at updated_at
250 1 'main' 2023-01-01 00:00:00 2023-01-01 00:00:00 I then get a model and sync the same exact IDs plus the same extra pivot data: $product = Product::find(1);
$synced = $product->categories()->sync([250 => ['type' => 'main']]); I would expect the result to be no changes to my database tables and I would expect $synced to have three empty arrays for attached, detached, and updated. Instead, The updated_at field gets updated and $synced['updated'] will have an entry. category_id product_id type created_at updated_at
250 1 'main' 2023-01-01 00:00:00 2023-01-03 11:09:53 [ 'attached' => [], 'detached' => [], 'updated' => [0 => 250], ] This behavior makes the return data of the sync method unreliable, causes extra database updates, and pollutes the updated_at field. This behavior is different than if you didn't include extra pivot data. If this was my data: category_id product_id type created_at updated_at
250 1 '' 2023-01-01 00:00:00 2023-01-01 00:00:00 And I synced just an id: $synced = $product->categories()->sync([250]); The result would be no updates to the database table and no logged updates in $synced. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
hi
i try to test eloquent relation belongsToMany .
after test, i see updated relation over and over without any data change.
url description: https://stackoverflow.com/questions/74967177/why-laravel-belongstomany-update-extra-pivot-column
check eloquent sync method in file :
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php
line 92:
$current = $this->getCurrentlyAttachedPivots() ->pluck($this->relatedPivotKey)->all();
line:95:
$records = $this->formatRecordsList($this->parseIds($ids));
line 113:
$changes = array_merge(
$changes, $this->attachNew($records, $current, false)
);
this method can not detect data is dirty or clean because data pluck only ids.
Beta Was this translation helpful? Give feedback.
All reactions