新建一个 common\helpers\ModelHelper.php
文件:
<?php
/**
* author : forecho <caizhenghai@gmail.com>
* createTime : 2016/12/27 19:26
* description:
*/
namespace common\helpers;
class ModelHelper
{
/**
* 批量插入数据保存
* 使用示例:
*
* $rows = [];
* foreach ($items as $key => $value) {
* $rows[$key]['title'] = $value['title'];
* $rows[$key]['user_id'] = $userId;
* }
* if (!ModelHelper::saveAll(Post::tableName(), $rows)) {
* throw new Exception();
* }
*
* @param $tableName
* @param array $rows
* @return int
* @throws \yii\db\Exception
*/
public static function saveAll($tableName, $rows = [])
{
if ($rows) {
return \Yii::$app->db->createCommand()
->batchInsert($tableName, array_keys(array_values($rows)[0]), $rows)
->execute();
}
return false;
}
}
缺点可能就是批量插入失败无法捕捉异常,还有就是无法触发 afterSave 和 beforeSave 事件。
本文由 forecho 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。
如果这篇文章对您有帮助,不妨微信小额赞助我一下,让我有动力继续写出高质量的教程。