您的位置:首页 > 编程语言 > PHP开发

Yii2框架 model方法下setAttributes用法(自定义model 添加方法)

2016-11-07 07:38 621 查看
正如我们知道的yii2框架中一般使用的增加数据有两种方式

1、使用createCommand()方法:

[php] view
plain copy

Yii::$app->db->createCommand()->insert('user', [    

    'name' => 'test',    

    'age' => 30,    

])->execute();  

2、使用model层save()方法:

[php] view
plain copy

$user= new User;           

$user->username =$username;    

$user->password =$password;    

$user->save()  

那么作文MVC为主角的Yii2框架  我们在添加数据的时候不能一条条的添加吧(low爆了);

此时我们可以在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($data as $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方法中定义字段规则了!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: