时间:2021-07-01 10:21:17 帮助过:13人阅读
1、在 common/config/main-local.php 里面配置数据账号和密码。
2、ActiveRecord(活动记录,简称AR类),提供了一套面向对象的接口,用以访问数据库中的数据
$model = Post::find()->where([‘id‘=>1])->one();
$model = Post::findOne(1);
$model = Post::find()->where([‘status‘=>1])->all();
$model = Post::findAll([‘status‘=>1]);
3、ActiveQueryInterface 常用方法:
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、yii\db\ActiveRecord::insert() // 插入
$customer = new Customer();
$customer -> name = ‘Carroll‘;
$customer -> email = ‘Carroll@qq.com‘
$customer -> save(); // 等同于 $customer -> insert()
b、yii\db\ActiveRecord::update() // 更新
$customer = Customer::findOne($id);
$customer -> email = ‘123456@qq.com‘
$customer ->save(); // 等同于 $customer -> update()
c、yii\db\ActiveRecord::delete() // 删除
$customer = Customer::findOne($id);
$customer -> delete();
d、yii\db\ActiveRecord::save() // 可同时替代 insert() 和 update(),开发中常用 save()方法
7 、ActiveRecord 的生命周期
yii2 数据库和ActiveRecord
标签:16px 生命周期 数据 mon soft model sample where 对象