2014-12-08 62 views

回答

42

您可以使用batchInsert()方法yii\db\Command。看詳情here。 與ActiveRecord一起使用時,請確保在插入前驗證所有數據。

假設你有$與Post級車型,它可以這樣做數組:

$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只是用於拉動attirubute名單,你也可以從你的$ models數組中的任何現有的$模型中拉出。

如果您不需要插入填充$rows陣列時,所有的屬性,你可以指定它:

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

不要忘記更換$postModel->attributes['title', 'content']

如果屬性數量較多,可以使用一些數組函數來指定插入的確切屬性。

+0

那麼,答案是否定的?我應該使用DAO。 – user1561346 2014-12-08 11:34:25

+0

我認爲ActiveRecord目前不支持這個框。你可以做一些進一步的研究,但是我找不到它。 – arogachev 2014-12-08 11:40:16

+1

$ postModel->屬性應該是$ postModel-> attributes() – Dodo 2015-05-30 12:02:38