Laravel 查询用旧数据替换新数据
Laravel query replace new data with old one
Basically this question is following of
As that question got too messy I want to separate the question here.
说明
我在我的 blade 中附加了行,其中将附加几个 select 框,我可以选择每个框的选项。此数据将保存在数据库中(到这里一切都很好)
问题
当我更改我的 selected 选项之一时出现,而不是更新它会将所有 select 作为新选项添加。
截图 1
代码
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)
的结果
有什么想法吗?
已解决
我已将函数更改为以下代码,现在一切正常
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);
}
希望对其他人有所帮助。
Basically this question is following of
As that question got too messy I want to separate the question here.
说明
我在我的 blade 中附加了行,其中将附加几个 select 框,我可以选择每个框的选项。此数据将保存在数据库中(到这里一切都很好)
问题
当我更改我的 selected 选项之一时出现,而不是更新它会将所有 select 作为新选项添加。
截图 1
代码
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)
有什么想法吗?
已解决
我已将函数更改为以下代码,现在一切正常
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);
}
希望对其他人有所帮助。