PHP框架 Laravel Eloquent ORM 批量插入数据 && 批量更新目前没有

foreach ($products as $v=>$a)
{
$count[] = array('product_name' => $a['name'], 'product_weight' => $a['weight'], 'product_id' => $a['pid'], 'product_price' => $a['price'], 'order_id' => $order->id, 'card_phone' => $user->phone);
}
CountOrder::insert($count);

在使用 laravel 的批量插入数据时,

插入的数据的创建时间却都是 0000000;

PHP框架 Laravel Eloquent ORM 批量插入数据 && 批量更新目前没有

创建时间 和 更新时间字段 如何正常保存呢 ,难道也要在数组里面写入吗?

 
 
 
 

框架封装好的方法目前是没有的,但是随手google了一下,在*上看到一个和你的这个问题非常匹配的回答,以下复制于*,原链接http://*.com/questions/26133977/laravel-bulk-update
I have created My Custom function for Multiple Update like update_batch in CodeIgniter.
Just place this function in any of your model or you can create helper class and place this function in that class:

//test data
/*
$multipleData = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
)
*/ /*
* ----------------------------------
* update batch
* ----------------------------------
*
* multiple update in one query
*
* tablename( required | string )
* multipleData ( required | array of array )
*/
static function updateBatch($tableName = "", $multipleData = array()){ if( $tableName && !empty($multipleData) ) { // column or fields to update
$updateColumn = array_keys($multipleData[0]);
$referenceColumn = $updateColumn[0]; //e.g id
unset($updateColumn[0]);
$whereIn = ""; $q = "UPDATE ".$tableName." SET ";
foreach ( $updateColumn as $uColumn ) {
$q .= $uColumn." = CASE "; foreach( $multipleData as $data ) {
$q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";
}
$q .= "ELSE ".$uColumn." END, ";
}
foreach( $multipleData as $data ) {
$whereIn .= "'".$data[$referenceColumn]."', ";
}
$q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (". rtrim($whereIn, ', ').")"; // Update
return DB::update(DB::raw($q)); } else {
return false;
}
}

It will Produces:

UPDATE `mytable` SET `name` = CASE
WHEN `title` = 'My title' THEN 'My Name 2'
WHEN `title` = 'Another title' THEN 'Another Name 2'
ELSE `name` END,
`date` = CASE
WHEN `title` = 'My title' THEN 'My date 2'
WHEN `title` = 'Another title' THEN 'Another date 2'
ELSE `date` END
WHERE `title` IN ('My title','Another title')
 
 
上一篇:Laravel Eloquent ORM


下一篇:Ybtoj 643. 「平衡树」机器决斗