cakephp – Cake 3:如何使用primaryKey设置将新实体添加到数据库?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了cakephp – Cake 3:如何使用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
> Converting Request Data
> Avoiding Property Mass Assignment Attacks
> Calidating Data Before Building Entities

脚本宝典总结

以上是脚本宝典为你收集整理的cakephp – Cake 3:如何使用primaryKey设置将新实体添加到数据库?全部内容,希望文章能够帮你解决cakephp – Cake 3:如何使用primaryKey设置将新实体添加到数据库?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。