常用于增加和修改,属于 ORM 的术语范畴。
新增数据
<?php
$customer = new Customer();
$customer->name = 'Qiang';
$customer->save();
// 新增后获取主键id,假设 id 为主键
echo $customer->id;
// 模型->主键,在save成功后,就可以获取到
// 注:一定要保证 $customer->save(); 的返回值不为 false
修改数据
<?php
$customer = Customer::findOne(123);
$customer->email = 'james@newexample.com';
$customer->save();
查找数据
<?php
$customer = Customer::findOne([
'id' => 123,
'status' => Customer::STATUS_ACTIVE,
]);
源码
Cutsomer 在声明的时候,并未显式指定其属性,那么其是在什么时候进行属性指定的呢?
schema使用的是 SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ‘数据库名’ AND table_name = ‘表名’
// BaseActiveRecord 中,当 $model->prop 的时候就可以执行到此方法
// hasAttribute()方法中 $this->attributes() 指向了 db/ActiveRecord的attributes方法
// array_keys(static::getTableSchema()->columns); 其获取了字段的内容
public function __set($name, $value)
{
if ($this->hasAttribute($name)) {
if (
!empty($this->_relationsDependencies[$name])
&& (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
) {
$this->resetDependentRelations($name);
}
$this->_attributes[$name] = $value;
} else {
parent::__set($name, $value);
}
}