yii2 ar的setAttributes方法注意
例如有这样一个model A:
(1)A对应到的表格为tableA
tableA中这样几个字段
字段 id name sex age
数据 1 test 男 18
(2)将一个新的数据插入到数据库中
有两种方法:
方法一:
$a = new A;
a->name = "test2";
a->sex = "女";
a->age = 20;
a->save();
方法二:
$a = new A;
$a->setAttributes(array("name"=>"test2","sex"=>"女","age"=>20));
$a->save();
但是使用方法二的时候要注意,如果在modelA中的rules方法中没有列出相应的字段,这个setArributes方法不会和数据库中的字段对应起来的
例如
model A中的rules为
public function rules() {
// NOTE: you should only define rules for those attributesthat
// will receive user inputs.
return array(
);
}
那么执行了save方法后,数据库中会插入一条数据,但是数据全为NULL,
如果想将字段对应起来,我们可以这样做:
public function rules() {
// NOTE: you should only define rules for those attributesthat
// will receive user inputs.
return array(
array("name, sex, age", "safe"),
);
}
这样数据就可以正常插入到数据库中了
方法三,使用setAttributes的第二个参数$safeOnly,设置为false,表示不检测字段安全
$a->setAttributes(array("name"=>"test2","sex"=>"女","age"=>20),false);
- 上一篇: 控制input输入只能是字母、数字、下划线
- 下一篇: android studio优化设置