在開發 酷瓜雲課堂(開源知識付費解決方案)的過程中,需要一次插入幾千條數據,官方文檔裏沒有相關批量操作的指引,自己動手才能豐衣足食。
Phalocn 默認的 Model 和 PHQL 是不支持批量插入記錄的,如果用循環插入幾百上千成萬的記錄,那效率不知道有多低。使用Phalcon底層的 db 操作可以支持原生 SQL,拼裝一下 SQL 語句就可以批量插入記錄了。
語句拼裝函數
/**
* 批量插入SQL
*
* @param string $table
* @param array $rows
* @return false|string
*/
function kg_batch_insert_sql($table, $rows = [])
{
if (count($rows) == 0) return false;
$fields = implode(',', array_keys($rows[0]));
$values = [];
foreach ($rows as $row) {
$items = array_map(function ($item) {
return sprintf("'%s'", htmlspecialchars($item, ENT_QUOTES));
}, $row);
$values[] = sprintf('(%s)', implode(',', $items));
}
$values = implode(',', $values);
return sprintf("INSERT INTO %s (%s) VALUES %s", $table, $fields, $values);
}
使用方法案例
$logModel = new QQDeliverLogModel();
$table = $logModel->getSource();
$rows = [];
$createTime = time();
foreach ($groupUsers as $groupUser) {
$rows[] = [
'task_id' => $task->id,
'group_id' => $groupUser->group_id,
'user_id' => $groupUser->user_id,
'create_time' => $createTime,
];
}
$sql = kg_batch_insert_sql($table, $rows);
try {
$this->db->begin();
$this->db->execute($sql);
$this->db->commit();
} catch (\Exception $e) {
$this->db->rollback();
}