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 的批量插入數據時,php

插入的數據的建立時間卻都是 0000000;laravel

圖片描述

建立時間 和 更新時間字段 如何正常保存呢 ,難道也要在數組裏面寫入嗎?sql

 
 
 
 

框架封裝好的方法目前是沒有的,可是隨手google了一下,在stackoverflow上看到一個和你的這個問題很是匹配的回答,如下複製於stackoverflow,原連接http://stackoverflow.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')
相關文章
相關標籤/搜索