首页 > thinkphp model 里面的add方法保存数组到数据库,在Yii2里面有什么方法可代替呢?

thinkphp model 里面的add方法保存数组到数据库,在Yii2里面有什么方法可代替呢?

thinkphp model 里面的add方法保存数组到数据库,在Yii2里面有什么方法可代替呢?

thinkphp  add方法

$insert = array();
$insert['name'] = '张三';
$insert['age']  = '25';
$model = M('Member');
$model->add($insert);

在Yii2 里面有什么方法能快速使数组key=>value 字段=>值 一一对应入库呢?
目前我看了手册后,自己封装了个比较笨的方法

/**
   * 插入数据
   * 
   * @param  array  $insert [description]
   * @return [type]         [description]
   */
   public function doInsert($insert=[])
   {

      $obj = new Member;

      if($insert)
      {
        foreach ($insert as $key => $value) 
        {
            $obj->$key = $value;
        }

         return $obj->insert();
      }
      
      return false;

   }// end function

Yii2 是OOP框架,楼主所说的 保存功能 在 Yii2 中有多种实现方案,建议使用 ActiveRecord

大概代码是这个样子的:


$member = new Member();
$member->name = '张三';
$member->age = 20;
$member->save();

Yii2 ActiveRecord文档


$userModel = new User;
$userModel->save(true|false,[
'username'=>1,
'password'=>2,
]);

save第一个参数为,是否运行检测数据。这个和前端的validata类似,相关规则在Model的rule里面定义。
另外 看如下代码,说明你需要用===来判断是否操作成功,如果他执行了update函数时,影响函数为0时,那么 == false就会成立。

    public function save($runValidation = true, $attributeNames = null)
    {
        if ($this->getIsNewRecord()) {
            return $this->insert($runValidation, $attributeNames);
        } else {
            return $this->update($runValidation, $attributeNames) !== false;
        }
    }

    public function getIsNewRecord()
    {
        return $this->_oldAttributes === null;
    }

model->load();
model->save();
这两个方法解决你的问题。手机回的。编码可能不对。


不用自己封装,这个基本的操作 Yii2 有提供,除了 @游梦惊园 提供的方法,还有下面这个方法:

$member = new Member();
$member->setAttributes([
    'name ' => '张三',
    'age ' => 20,
]);
$member->save();
【热门文章】
【热门文章】