常用于增加和修改,属于 ORM 的术语范畴。

新增数据

  1. <?php
  2. $customer = new Customer();
  3. $customer->name = 'Qiang';
  4. $customer->save();
  5. // 新增后获取主键id,假设 id 为主键
  6. echo $customer->id;
  7. // 模型->主键,在save成功后,就可以获取到
  8. // 注:一定要保证 $customer->save(); 的返回值不为 false

修改数据

  1. <?php
  2. $customer = Customer::findOne(123);
  3. $customer->email = 'james@newexample.com';
  4. $customer->save();

查找数据

  1. <?php
  2. $customer = Customer::findOne([
  3. 'id' => 123,
  4. 'status' => Customer::STATUS_ACTIVE,
  5. ]);

源码

Cutsomer 在声明的时候,并未显式指定其属性,那么其是在什么时候进行属性指定的呢?

schema使用的是 SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ‘数据库名’ AND table_name = ‘表名’

  1. // BaseActiveRecord 中,当 $model->prop 的时候就可以执行到此方法
  2. // hasAttribute()方法中 $this->attributes() 指向了 db/ActiveRecord的attributes方法
  3. // array_keys(static::getTableSchema()->columns); 其获取了字段的内容
  4. public function __set($name, $value)
  5. {
  6. if ($this->hasAttribute($name)) {
  7. if (
  8. !empty($this->_relationsDependencies[$name])
  9. && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
  10. ) {
  11. $this->resetDependentRelations($name);
  12. }
  13. $this->_attributes[$name] = $value;
  14. } else {
  15. parent::__set($name, $value);
  16. }
  17. }