ActiveRecord batch insert (yii2)(ActiveRecord 批量插入 (yii2))
问题描述
是否可以使用 Yii 的 ActiveRecord 在一个查询中插入多行?或者这只能通过较低级别的 DAO 对象实现?
Is it possible to insert multiple rows in one query with Yii's ActiveRecord? Or is this only possible via the lower-level DAO objects?
我有两个模型1- 交易2-TransactionItems
I have two models 1- Transaction 2-TransactionItems
事务项中有多行(点击添加行).
There are multiple rows(onclick add row) in transaction Items.
我想在数据库中存储多行事务项.
I want to store multiple rows of transactionitems in the database.
交易项目表截图
推荐答案
你可以使用yiidbCommand的batchInsert()方法.查看详情这里.与 ActiveRecord 一起使用时,请确保在插入前验证所有数据.
You can use batchInsert() method of yiidbCommand. See details here.
When using it with ActiveRecord make sure validate all data before inserting.
假设您有一组带有 Post 类的 $models,可以这样做:
Assuming you have array of $models with class Post, it can be done like this:
$rows = [];
foreach ($models as $model) {
if (!$model->validate()) {
// At least one model has invalid data
break;
}
$rows[] = $model->attributes;
}
如果模型不需要验证,您可以使用 ArrayHelper 缩短上面的代码以构建 $rows 数组.
If models don't require validation you can short the code above using ArrayHelper for building $rows array.
use yiihelpersArrayHelper;
$rows = ArrayHelper::getColumn($models, 'attributes');
然后简单地执行批量插入:
Then simply execute batch insert:
$postModel = new Post;
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();
附言$postModel 仅用于提取属性名称列表,您也可以从 $models 数组中的任何现有 $model 中提取它.
P.S. The $postModel just used for pulling attirubute names list, you can also pull this from any existing $model in your $models array.
如果不需要插入所有属性,可以在填充$rows数组时指定:
If you don't need to insert all attributes you can specify it when filling $rows array:
$rows[] = [
'title' => $model->title,
'content' => $model->content,
];
不要忘记将 $postModel->attributes 替换为 ['title', 'content'].
Don't forget to replace $postModel->attributes to ['title', 'content'].
如果属性较多,您可以使用一些数组函数来指定要插入的确切属性.
In case of larger amount of attributes you can use some array functions to specify exact attributes for inserting.
这篇关于ActiveRecord 批量插入 (yii2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ActiveRecord 批量插入 (yii2)
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
