laravel - laravle Eloquent ORM 一次update多条记录
phpcn_u1582
phpcn_u1582 2017-05-16 16:54:58
0
1
555

Eloquent 批量更新多条记录

不是对一条记录多个字段批量赋值,
而是根据不同条件对不同记录做不同修改

类似 批量插入:

DB::table('users')->insert(array(

array('email' => 'taylor@example.com', 'votes' => 0),

array('email' => 'dayle@example.com', 'votes' => 0),

));

有没有类似的语句

DB::table('users')->update( array(

array('id'=>1, 'email' => 'taylor1@example.com', 'votes' => 1),

array('id'=>2, 'email' => 'dayle2@example.com', 'votes' => 2),

) , 'id' );

实现的功能是:
根据id修改相应的记录:

id=1 'email' 修改成'taylor1@example.com', 'votes' 修改成 1,
id=2 'email' 修改成'dayle2@example.com', 'votes' 修改为 2
。。。

ci是有类似的update_batch方法,想转换成laravel,请多指点了。

phpcn_u1582
phpcn_u1582

全部回复(1)
为情所困

框架封装好的方法目前是没有的,但是随手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')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!