Laravel issue: Problem updating hasMany relationship record
P粉054616867
2023-08-30 21:47:17
<p>I have a User model that has a hasMany relationship with a Brand model, and I'm having trouble updating the user's Brand correctly. </p>
<p>I have a form that allows users to enter/remove/update their own brand in a text field, the method I currently use to update a user's brand after the user enters or edits the brand is to delete all existing brands associated with the user , then loop through the values, create the brand model, then "saveMany"...but I seem to get a constraint conflict when adding...I'm wondering if there's a better way to do this; < /p>
<p>My <code>User</code> model has the following;</p>
<pre class="brush:php;toolbar:false;">public function brands()
{
return $this->hasMany('Brands::class');
}
</pre>
<p>Then in my controller I have the following code to update the brand;</p>
<pre class="brush:php;toolbar:false;">$user->brands()->delete();
foreach ($request['brands'] as $brand) {
$brandArray[] = new Brand([
'name' => $brand['name'],
'rating' => $brand['rating'],
]);
}
!empty($brandArray) && $user->brands()->saveMany($brandArray);
</pre>
<p>Is there a better way? </p>
Let’s break things into three parts:
# Constraint key violation:
If you added a foreign key constraint on another table and need to delete the brand, you should also delete all related data constrained by the foreign key.
# design
If the brand related data cannot be removed, then maybe we can consider if there is a better design. Maybe we can add a hook on the frontend that calls the DELETE API whenever the user deletes some data.
# Inquire
If the brand has some unique keys, you can use
upsert
instead of saveMany. This will be more efficient.#in conclusion
I recommend deleting the brand via a hook on the frontend whenever the user deletes it, and using
upsert
to handlecreating and updating
content