【问题标题】:ActiveRecord batch insert (yii2) [closed]ActiveRecord 批量插入(yii2)[关闭]
【发布时间】:2015-02-05 22:44:04
【问题描述】:

是否可以使用 Yii 的 ActiveRecord 在一个查询中插入多行?或者这只能通过较低级别的 DAO 对象实现?

我有两个模型 1- 交易 2-TransactionItems

事务项中有多行(onclick add row)。

我想在数据库中存储多行事务项。

Screenshot of Transaction item table

【问题讨论】:

    标签: php yii2 dao batch-insert


    【解决方案1】:

    您可以使用yii\db\Command 的batchInsert() 方法。详情见here。 与ActiveRecord 一起使用时,请确保在插入之前验证所有数据。

    假设你有一个类为Post 的 $models 数组,可以这样完成:

    $rows = [];
    foreach ($models as $model) {
        if (!$model->validate()) {
            // At least one model has invalid data
    
            break;
        }
    
        $rows[] = $model->attributes;
    }
    

    如果模型不需要验证,您可以使用 ArrayHelper 缩短上面的代码以构建 $rows 数组。

    use yii\helpers\ArrayHelper;
    
    $rows = ArrayHelper::getColumn($models, 'attributes');
    

    然后直接执行批量插入:

    $postModel = new Post;
    
    Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $postModel->attributes(), $rows)->execute();
    

    附: $postModel 仅用于拉取属性名称列表,您也可以从 $models 数组中的任何现有 $model 中拉取它。

    如果不需要插入所有属性可以在填充$rows数组时指定:

    $rows[] = [
        'title' => $model->title,
        'content' => $model->content,
    ];
    

    不要忘记将$postModel->attributes 替换为['title', 'content']。

    如果属性数量较大,您可以使用一些数组函数来指定插入的确切属性。

    【讨论】:

    • 那么,答案是否定的?我应该使用 DAO。
    • 我认为目前 ActiveRecord 不支持此功能。你可以做一些进一步的研究,但我找不到。
    • $postModel->attributes 应该是 $postModel->attributes()
    • @Dodo 感谢您的评论,更正了答案。
    • @arogachev:如何在批量插入中获取所有 laster 插入 id?
    猜你喜欢
    • 2017-01-28
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多