天天看點

yii2 save update 數組指派操作

原文轉自   IT技術擎

有的我們通過各種的資料處理,傳回了處理好的資料 想把這些處理好了數組的資料插入或是更新 到庫裡面去

有兩種辦法

1、使用自帶的方法setAttributes()

下面的代碼就是把fields處理的數組資料插入到資料庫裡面去

        $pdata = $model->toArray();

        $model->setAttributes($pdata);

        $model->save()

2、使用對象指派的方式來給資料元素指派

$pdata = $model->toArray();

       $model->region_name = $pdata['region_name'];

        $model->pinyin = $pdata['pinyin'];

        $model->save()

以上這兩種方式  都可以達到同樣的效果