cakephp – Cake 3:如何使用primaryKey设置将新实体添加到数据
发布时间:2020-12-13 14:14:51 所属栏目:PHP教程 来源:网络整理
导读:我想用从excel表中提取的“flat”数据填充我的数据库.所有记录都以数组形式提供(类似于$request-数据),但其primaryKeys设置必须保留哪些值. 我的代码: $imported = 0; foreach ($data as $record) { $entity = $table-findOrCreate([$table-primaryKey() =
我想用从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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |