我想用从excel表中提取的"flat"数据填充我的数据库.所有记录都以数组形式提供(类似于$ request-> data),但其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++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码有效,但我想知道是否有更好的解决方案?
澄清:我想要的是添加类似的内容
[
['id' => 25, 'title'=>'some title'],
['id'=> 3, 'title' => 'some other title'],
['id' => 4356, 'title' => 'another title']
]
Run Code Online (Sandbox Code Playgroud)
到我的空数据库.findOrCreate()完成这项工作.但我认为没有必要在插入之前测试数据库中尚未存在的每条记录.