-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.8] Fix many to many sync results with custom pivot model #28416
Conversation
Hey @themsaid, I think this PR caused a breaking change for me when trying to use updateExistingPivot when there were no records found:
My code snippet: Did I use it wrong or is it broken when no records are found? |
@pdewit if there are no records found then it's not an existing pivot, not sure why you're using |
Hello @themsaid, |
At least this PR contains breaking change. Previous:
Now:
@themsaid If so, when do you think you should use this method? It looks very difficult to use. Should we always use @themsaid @pdewit @lk77 @taylorotwell Any ideas? |
How about this? /**
* Update an existing pivot record on the table via a custom class.
*
* @param mixed $id
* @param array $attributes
* @param bool $touch
* @return int
*/
protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch)
{
- $updated = $this->getCurrentlyAttachedPivots()
- ->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
- ->where($this->relatedPivotKey, $this->parseId($id))
- ->first()
- ->fill($attributes)
- ->isDirty();
-
+ $pivot = $this->getCurrentlyAttachedPivots()
+ ->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
+ ->where($this->relatedPivotKey, $this->parseId($id))
+ ->first();
+
+ $updated = $pivot ? $pivot->fill($attributes)->isDitry() : false;
$this->newPivot([
$this->foreignPivotKey => $this->parent->{$this->parentKey},
$this->relatedPivotKey => $this->parseId($id),
], true)->fill($attributes)->save();
if ($touch) {
$this->touchIfTouching();
}
return (int) $updated;
} |
This PR fixes an issue (#28150) where the results of
sync()
while updating "Custom Pivot Model" attributes always show the record as updated even if it's not.The reason was that we weren't loading the actual pivot model from the database and thus we didn't have any way to compare the newly provided data with the existing one.
My solution here is that we load the model from the database first, and use
isDirty()
to check if the attributes were update or not.