我真的在使用laravel ON DUPLICATE KEY UPDATE查询我无法让它工作,所以查询基本上看起来像
foreach ($queries as $query) {
$update_time = array('update_time' => date('Y-m-d H:i:s'));
$query = array_merge($update_time, $query);
$keysString = implode(", ", array_keys($query));
$indexes = "";
$values = "";
$updates = "";
foreach ($query as $i=>$v){
$values .= ':'.$v.',';
$updates .= $i.'="'.$v.'",';
}
//$holder = rtrim(str_repeat('?,', count($query)),',');
$updates = rtrim($updates,',');
DB::statement("INSERT INTO products ({$keysString}) VALUES ({rtrim($values,',')}) ON DUPLICATE KEY UPDATE {rtrim($updates,',')}")
}
但我得到
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
如何在laravel4中为原始查询制作预备声明?
答案 0 :(得分:0)
默认情况下,Laravel使用?
绑定其数据,并且您将数据绑定到:foo
,这意味着这两种方法混合在一起,PDO对此感到悲伤。
PDO: Invalid parameter number: mixed named and positional parameters
这样的事情会让你朝着正确的方向前进:
foreach ($queries as $query) {
// Add the update time without merging stuff
$query['update_time'] = date('Y-m-d H:i:s');
// How many bits of data do we have
$bindingCount = count($query);
// Same as before, just get the keys
$keyString = implode(", ", array_keys($query));
// Start off a bindings array with just the values
$bindings = array_values($query);
$updates = [];
foreach ($query as $field => $value){
$updates[] = "{$field} = ?";
$bindings[] = $value;
}
$valueString = implode(',', array_fill(0, $bindingCount, '?'));
$updateString = implode(',', $updates);
DB::statement("INSERT INTO products ({$keyString}) VALUES ({$valueString}) ON DUPLICATE KEY UPDATE {$updateString}", $bindings);
}