Laravel查询用旧数据替换新数据 [英] Laravel query replace new data with old one
本文介绍了Laravel查询用旧数据替换新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,这个问题是在 [link]
这个问题太混乱了,我想在这里分开这个问题.
As that question got too messy I want to separate the question here.
说明
我在刀片中添加了行,其中将添加几个选择框,我可以选择每个行的选项.这些数据将保存在数据库中(直到这里一切都很好)
会在我更改所选选项之一时出现,而不是进行更新,而是将所有选择都添加为新选项.
comes when I change one of my selected options and instead of being update it will add all selects as new one.
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
}
屏幕截图2
dd($spec)
有什么主意吗?
推荐答案
已解决
我将函数更改为下面的代码,现在一切正常
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.
这篇关于Laravel查询用旧数据替换新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文