0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP2でsaveAllが遅いからバルクインサート

Last updated at Posted at 2020-04-29

こちらのサイトから引用させていただきました
http://damepg.hatenablog.com/entry/2012/10/01/001223

saveAllとqueryでのバルクインサートでは50倍の差があるみたいです。

バルクインサート

どのテーブルでも使えるので、AppModelにでも。

    // バルクインサート
	public function bulkInsert($data) {
		$table_name = $this->usetable;
		$fields = array_keys($data[0]);

		$holder = '(' . implode(',', array_fill(0, count($fields), '?')) . ')';
		$holders = implode(',', array_fill(0, count($data), $holder));

		$params = array();
		foreach ($data as $key => $val) {
			foreach ($fields as $field) {
				if ($field == 'created') {
					$params[] = date('Y-m-d H:i:s');
				} else {
					$params[] = $val[$field];
				}
			}
		}

		$fields = implode(',', $fields);
		$sql = "INSERT INTO ${table_name} (${fields}) VALUES ${holders}";

		$ret = $this->query($sql, $params);
		if ($ret === false) {
			// エラー処理
			return false;
		}
		if ($this->getAffectedRows() != count($data)) {
			// エラー処理
			return false;
		}

		return true;
	}

使い方

    // Model指定して使う
	$this->User->bulkInsert(
		array(
			array( 'name' => 'taro','job' =>  '社長'),
			array( 'name' => 'jiro','job' =>  '専務'),
			array( 'name' => 'saburo','job' => 'バイト'),
		)
	);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?