如何实现“插入忽略”?使用kohana orm添加多条记录时,如果使用下面的代码,数据库中可能已经存在少量记录,则会拒绝添加所有100条记录。
$query = DB::insert('tablename', array('column1', 'column2','column3'));
foreach ($data as $d) {
$query->values($d);
}
try {
$result = $query->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
更新 这是我如何做到这一点,我必须插入多个记录,
$Xtransactions = "INSERT IGNORE INTO `tablename` (`tid`, `tdate`, `appid`,
`userid`, `user_ip`) VALUES";
foreach ($objSas->trecord as $trow) {
$Xtransactions .= "(".$trow->tid.",'".
date('Y-m-d H:i:s', strtotime($trow->tdate))."',".
$trow->userid.",".
$trow->Xnumber.",'".
$trow->ip."'),";
}
$Xtransactions = substr($Xtransactions , 0, -1);
try {
DB::query(Database::INSERT, $Xtransactions )->execute();
} catch ( Database_Exception $e ) {
echo $e->getMessage();
}
答案 0 :(得分:2)
使用查询构建器,这是不可能的,尝试编写原始查询。
DB::query(Database::INSERT, 'INSERT IGNORE INTO table VALUES (...)')->execute();
答案 1 :(得分:1)
我通常在静态助手类中收集此类修改,例如
<?php defined('SYSPATH') or die('No direct script access.');
class Helper_DB_Query{
/**
* @param Database_Query_Builder_Insert $insert query thant need to be converted
* @return Database_Query converted query
*/
public static function insert_to_insert_ignore( Database_Query_Builder_Insert $insert ){
$insert = (string) $insert;
$query = preg_replace("/^INSERT(.*)$/", "INSERT IGNORE $1", $insert);
return DB::query(Database::INSERT, $query);
}
}