我想用从excel表中提取的“flat”数据填充我的数据库.所有记录都以数组形式提供(类似于$request->数据),但其primaryKeys设置必须保留哪些值.
我的代码:
我的代码:
$imported = 0;
foreach ($data as $record) {
$entity = $table->findOrCreate([$table->primaryKey() => $record[$table->primaryKey()]]);
$entity = $table->patchEntity($entity,$record);
if ($table->save($entity)) {
$imported++;
}
}
代码有效,但我想知道是否有更好的解决方案?
澄清:我想要的是添加类似的内容
[ ['id' => 25,'title'=>'some title'],['id'=> 3,'title' => 'some other title'],['id' => 4356,'title' => 'another title'] ]
到我的空数据库. findOrCreate()完成这项工作.但我认为没有必要在插入之前测试数据库中尚未存在的每条记录.
如果你真的只使用空表,那么你可以直接保存数据,无需查找和修补,只需保存已禁用的存在检查.
此外,通过查看您的代码,数据似乎是一种可以立即转换为实体的格式,因此您可能希望一次创建它们.
$entities = $table->newEntities($data,[
// don't forget to restrict assignment one way or
// another when working with external input,for
// example by using the `fieldList` option
'fieldList' => [
'id','title'
]
]);
// you may want to check the validation results here before saving
foreach ($entities as $entity) {
if ($table->save($entity,['checkExisting' => false])) {
// ...
}
// ...
}
也可以看看
> Saving Entities
> Converting Request Data
> Avoiding Property Mass Assignment Attacks
> Calidating Data Before Building Entities