yii2 数据库和ActiveRecord

Yii2数据库和 ActiveRecord 类

1、common/config/main-local.php 里面配置数据账号和密码。

2、ActiveRecord(活动记录,简称AR类),提供了一套面向对象的接口,用以访问数据库中的数据

  • 一个AR类关联一张数据表,每个AR对象对应表中的一行;
  • AR类的属性,对应为数据库中的列
  • 可以以面向对象的方式来操纵数据库中的数据,这样就不用谢 sql 语句来实现数据库的访问。
  • find() 方法返回一条记录;
$model = Post::find()->where(['id'=>1])->one();
$model = Post::findOne(1);
  • find() 方法返回所有记录;
$model = Post::find()->where(['status'=>1])->all();
$model = Post::findAll(['status'=>1]);
$total = User::find()->count(); // 查询总数(count(*))

3、ActiveQueryInterface 常用方法:

  • all() 、one() --------- 执行查询,并返回 AR 对象
  • orderBy()、andOrderBy()  ---------  排序
  • count()  ---------  返回符合查询条件的记录数
  • limit()  ---------  取出查询结果的条数
  • with()  ---------  指定关联表的字段
  • where()、andWhere()、orWhere()  ---------  查询条件


4、where() 查询条件的写法:

  where 参数的写法 sql 语句
and  ['and','id=1','id=2'] id=1 AND id=2
or ['or','id=1','id=2'] id=1 OR id=2
in ['in','id',[1,2,3]] IN(1,2,3)
between ['between','id',1,10] id BETWEEN 1 AND 10
like ['like','name',['test','sample']] name LIKE '%test%' AND name LIKE '%sample%'
比较 ['>=','id',10] id >= 10

5、findBySql()

  $sql = "SELECT * FROM post WHERE status = 1";

  $post = Post::findBySql($sql) -> all();

6、CRUD 操作数据

AR 提供下面这些方法来实现插入、更新、删除等功能
a、yiidbActiveRecord::insert()   // 插入

$customer = new Customer();
$customer -> name = 'Carroll';
$customer -> email = 'Carroll@qq.com'
$customer -> save(); // 等同于 $customer -> insert()

b、yiidbActiveRecord::update()   // 更新

$customer = Customer::findOne($id);
$customer -> email = '123456@qq.com'
$customer ->save(); // 等同于 $customer -> update()

c、yiidbActiveRecord::delete()   // 删除

$customer = Customer::findOne($id);
$customer -> delete();

d、yiidbActiveRecord::save()    // 可同时替代 insert() 和 update(),开发中常用 save()方法

7 、ActiveRecord 的生命周期

方法          生命周期  事件
new()    1、constructor  
2、init()    EVENT_INIT
find()  1、constructor  
2、init() EVENT_INIT
3、afterFind()  EVENT_AFTER_FIND
save() 1、beforeValidate() EVENT_BEFORE_VALIDATE
2、执行数据验证,如通不过,则第三部后面的步骤会被略过  
3、afterValidate()  EVENT_AFTER_VALIDATE
4、beforeSave() EVENT_BEFORE_INSERT or EVENT_BEFORE_UPDATE
5、执行数据插入或修改  
6、afterSave() EVENT_AFTER_INSERT or EVENT_AFTER_UPDATE
delete() 1、beforeDelete() EVENT_BEFORE_DELETE
2、执行数据删除  
3、afterDelete()   EVENT_AFTER_DELETE
refresh() 1、afterRefresh() EVENT_AFTER_REFRESH

可以根据 ActiveRecord 的什么周期来重写方法,注入自己的代码控制流程

例如重写beforeSave(),如果这个方法执行后的结果为 false,后面的步骤就不会执行

    /**
     * @purpose : 将数据插入时间和更新时间插入数据库
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert){
        if(parent::beforeSave($insert)){                // 需要首先继承父类的 beforeSave()
            if($insert){
                $this->create_time = time();
                $this->update_time = time();
            }else{
                $this->update_time = time();
            }
            return true;
        }else{
            return false;
        }
    }

 查询所有的记录:

$dataProvider->query->each()

查询当前页的数据:
$dataProvider->getModels()

获取当前模型的默认值:
$model = new Test();
$model->loadDefaultValues();  // 当前模型的默认值
Yii 中的回滚操作,此处用于 当遇到 try .... cache() 的时候
$transacton = Yii::$app->dbName->beginTransaction();
try{
    ...
    $model->save();  
    $transacton->commit();
}cache(Exception $e){
   $transacton->rollBack();
   var_dump($e->getMessage());  
}



注:本文为作者(44106-kangaroo) 看完魏羲教你学Yii2.0 视频后所记,如有转载请注明出处:http://www.cnblogs.com/chrdai/p/8006425.html

原文地址:https://www.cnblogs.com/chrdai/p/8006425.html