php ActiveRecord 批量插入 (yii2)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27355262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActiveRecord batch insert (yii2)
提问by user1561346
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?
是否可以使用 Yii 的 ActiveRecord 在一个查询中插入多行?或者这只能通过较低级别的 DAO 对象实现?
回答by arogachev
You can use batchInsert()
method of yii\db\Command
. See details here.
When using it with ActiveRecord
make sure validate all data before inserting.
您可以使用 的batchInsert()
方法yii\db\Command
。在此处查看详细信息。使用它时,请ActiveRecord
确保在插入前验证所有数据。
Assuming you have array of $models with class Post
, it can be done like this:
假设你有一个带有 class 的 $models 数组Post
,它可以像这样完成:
$rows = [];
foreach ($models as $model) {
if (!$model->validate()) {
// At least one model has invalid data
break;
}
$rows[] = $model->attributes;
}
If models don't require validation you can short the code above using ArrayHelper
for building $rows
array.
如果模型不需要验证,您可以缩短上面ArrayHelper
用于构建$rows
数组的代码。
use yii\helpers\ArrayHelper;
$rows = ArrayHelper::getColumn($models, 'attributes');
Then simply execute batch insert:
然后简单地执行批量插入:
$postModel = new Post;
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();
P.S. The $postModel
just used for pulling attirubute names list, you can also pull this from any existing $model in your $models array.
PS$postModel
仅用于拉取属性名称列表,您也可以从 $models 数组中的任何现有 $model 中提取它。
If you don't need to insert all attributes you can specify it when filling $rows
array:
如果不需要插入所有属性,可以在填充$rows
数组时指定它:
$rows[] = [
'title' => $model->title,
'content' => $model->content,
];
Don't forget to replace $postModel->attributes
to ['title', 'content']
.
不要忘记替换$postModel->attributes
为['title', 'content']
.
In case of larger amount of attributes you can use some array functions to specify exact attributes for inserting.
在大量属性的情况下,您可以使用一些数组函数来指定要插入的确切属性。