我有一个包含很多字段的表单,每个字段都必须作为不同的行添加到表中。
我的桌子看起来像这样:
| Category | Device | Value |
|----------|:-------|-------------|
| 2 | 1 | some value |
| 3 | 1 | other value |
| 7 | 3 | etc |
类别和设备实际上是Categories
和Devices
表中的外键。此外,他们应该是唯一的,这意味着不能Category: 2
和Device: 1
的两倍。如果它们已经存在,则应更新该值。
从表单中检索类别和值,它看起来像这样:
{"2":"some value","3":"other value","5":"etc","6":"something","8":"can be empty"}
该设备也来自表格,但将是相同的。
现在,我需要在数据库中输入所有内容,并且正在寻找一个简单的解决方案。
但是它将执行约100个查询(每个输入一个查询),我敢肯定必须有一个更好的解决方案。
如果来自表单的值之一为空,则应将其忽略。
这是我当前正在工作的代码,也许您可以更好地理解:
public function postSpecs(Request $request)
{
$specs = $request->except(['_token', 'deviceid']);
foreach($specs as $key=>$val)
{
if($val == '') continue;
if(Spec::where('category', $key)->where('device', $request->deviceid)->exists())
{
$spec = Spec::where('category', $key)->where('device', $request->deviceid)->first();
$spec->value = $val;
$spec->save();
}
else
{
$spec = new Spec;
$spec->category = $key;
$spec->device = $request->deviceid;
$spec->value = $val;
$spec->save();
}
}
}
使用如下的insert方法:
$model->insert([
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
]);
另请参阅:http : //laravel.com/docs/5.1/queries#inserts
编辑:
更新为您的代码:
public function postSpecs(Request $request)
{
$specs = $request->except(['_token', 'deviceid']);
$data = array();
foreach($specs as $key=>$val)
{
if($val == '') continue;
if(Spec::where('category', $key)->where('device', $request->deviceid)->exists())
{
$spec = Spec::where('category', $key)->where('device', $request->deviceid)->first();
$spec->value = $val;
$spec->save();
}
else
{
$data[]['category'] = $key;
$data[]['device'] = $request->deviceid;
$data[]['value'] = $val;
}
}
Spec::insert($data);
}
虽然这不是完美的方法,但是它将为您节省很多查询。否则,您必须使用原始查询,例如(unested!):
INSERT INTO spec (id,category,device,value) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE id=LAST_INSERTED_ID(id)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句