This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
documents:cakephp_best_practice [2015/04/25 14:08] admin |
documents:cakephp_best_practice [2015/04/25 14:19] (current) admin |
||
---|---|---|---|
Line 2: | Line 2: | ||
=== 1. Save large record set === | === 1. Save large record set === | ||
+ | If we have to insert **<color green>large data</color>**, existed method saveAll() will be slow rather than core query. | ||
- | <php> | + | <PHP> |
public function submitData($data = array()) { | public function submitData($data = array()) { | ||
+ | |||
if (!empty($data)) { | if (!empty($data)) { | ||
- | $queryString = ''; | + | $queryString = ''; |
- | $queryData = array(); | + | $queryData = array(); |
- | $i = 0; | + | $i = 0; |
- | foreach ($data as $item) { | + | foreach ($data as $item) { |
if (empty($queryString)) { | if (empty($queryString)) { | ||
- | $queryString = "INSERT INTO `shipstations` ("; | + | $queryString = "INSERT INTO `tablename` ("; |
- | $columns = array(); | + | $columns = array(); |
- | $values = array(); | + | $values = array(); |
- | foreach($item as $key=>$value) { | + | foreach($item as $key=>$value) { |
$columns[] = "`$key`"; | $columns[] = "`$key`"; | ||
$values[] = !is_numeric($value) ? "'" . Utils::mres($value) . "'" : $value; | $values[] = !is_numeric($value) ? "'" . Utils::mres($value) . "'" : $value; | ||
- | } | + | } |
- | $queryString .= implode(',', $columns) . ') VALUES '; | + | $queryString .= implode(',', $columns) . ') VALUES '; |
- | $queryData[] = '(' . implode(',', $values) . ')'; | + | $queryData[] = '(' . implode(',', $values) . ')'; |
} else { | } else { | ||
- | $values = array(); | + | $values = array(); |
- | foreach($item as $key=>$value) { | + | foreach($item as $key=>$value) { |
- | $values[] = !is_numeric($value) ? "'" . $value . "'" : $value; | + | $values[] = !is_numeric($value) ? "'" . $value . "'" : $value; |
+ | } | ||
+ | $queryData[] = '(' . implode(',', $values) . ')'; | ||
} | } | ||
- | $queryData[] = '(' . implode(',', $values) . ')'; | ||
- | } | ||
- | $i++; | + | $i++; |
- | if ($i == 500) { | + | if ($i == 500) { |
- | $queryString .= implode(',', $queryData); | + | $queryString .= implode(',', $queryData); |
+ | $this->query($queryString); | ||
+ | $queryString = ''; | ||
+ | $queryData = array(); | ||
+ | $i = 0; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | $queryString .= implode(',', $queryData); | ||
+ | if (!empty($queryString)) { | ||
$this->query($queryString); | $this->query($queryString); | ||
- | $queryString = ''; | + | } |
- | $queryData = array(); | + | |
- | $i = 0; | + | |
- | } | + | |
} | } | ||
- | |||
- | $queryString .= implode(',', $queryData); | ||
- | if (!empty($queryString)) { | ||
- | $this->query($queryString); | ||
- | } | ||
- | } | ||
} | } | ||
- | </php> | + | </PHP> |