问题
Basically this question is following of [link]
As that question got too messy I want to separate the question here.
Explanation
I have appended rows in my blade where several select box will append and i can choose options of each of them. this data will save in database (Until here everything is good)
The issue
comes when I change one of my selected options and instead of being update it will add all selects as new one.
Screenshot 1
Code
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
// get all selected option
$looped = $request->subspecifications;
$spec = [];
if(!empty($looped)){ //check if there is any select box without option
foreach($looped as $sub) {
$sub = Subspecification::find($sub);
if (!empty($sub->id)) {
$data = (
[
'product_id' => $request->product_id,
'subspecification_id' => $sub->id,
]
);
array_push($spec, $data);
}
}
}
dd($spec);
// DB::table('product_subspecification')->insert($spec); // save data to database
}
Screenshot 2
results of dd($spec)
Any idea?
回答1:
Solved
I've changed my function to code below and now everything working fine
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$collection = collect($request->subspecifications)->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});
$product = Product::find($request->product_id);
$product->subspecifications()->sync($collection);
}
Hope it help others.
来源:https://stackoverflow.com/questions/52416297/laravel-query-replace-new-data-with-old-one