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

正如我们知道的yii2框架中一般使用的增加数据有两种方式

1、使用createCommand()方法:

Yii::$app->db->createCommand()->insert('user', [  
    'name' => 'test',  
    'age' => 30,  
])->execute();
2、使用model层save()方法:

$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方法中定义字段规则了!!!









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值