Yii2框架 model方法下setAttributes用法(自定義model 新增方法)
阿新 • • 發佈:2019-02-18
正如我們知道的yii2框架中一般使用的增加資料有兩種方式
1、使用createCommand()方法:
Yii::$app->db->createCommand()->insert('user', [
'name' => 'test',
'age' => 30,
])->execute();
2、使用model層save()方法:
那麼作文MVC為主角的Yii2框架 我們在新增資料的時候不能一條條的新增吧(low爆了);$user= new User; $user->username =$username; $user->password =$password; $user->save()
此時我們可以在model層建立我們自己定義的方法eg:add
廢話不多說我們直接上程式碼
model層
public function add($data) { $this->setAttributes($data); $this->isNewRecord = true; $this->save(); return $this->id; }
//入庫二維陣列 public function addAll($data){ $ids=array(); foreach($dataas $attributes) { $this->isNewRecord = true; $this->setAttributes($attributes); $this->save()&& array_push($ids,$this->id) && $this->id=0; } return $ids; }
public function rules() { return [ [['title','content'],'required' ]]; }控制器
public function actionAdd(){$model=new ListtModel; $data=array("title"=>"小白","content"=>"lala"); $id=$model->add($data); echo $id;
// $data=array( // array("title"=>"小白","content"=>"lala"),array("title"=>"小hong","content"=>"66") // ); // $ids=$model->addAll($data); // var_dump($ids);}
注意:我們一定要把欄位定義在model層rouls方法中下面我們去看看 model中setAttributes方法首先我們找到該方法的位置vendor/yiisoft/yii2/base/Model.php 檔案
/** * Sets the attribute values in a massive way. * @param array $values attribute values (name => value) to be assigned to the model. * @param boolean $safeOnly whether the assignments should only be done to the safe attributes. * A safe attribute is one that is associated with a validation rule in the current [[scenario]]. * @see safeAttributes() * @see attributes() */ public function setAttributes($values, $safeOnly = true) { if (is_array($values)) { $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes()); foreach ($values as $name => $value) { if (isset($attributes[$name])) { $this->$name = $value; } elseif ($safeOnly) { $this->onUnsafeAttribute($name, $value); } } } }
使用setAttributes的第二個引數$safeOnly,設定為false,表示不檢測欄位安全
$model->setAttributes(array('title'=>'小白','content'=>'lala'),false); 就可以不用在rules方法中定義欄位規則了!!!