码迷,mamicode.com
首页 > 数据库 > 详细

yii2 数据库和ActiveRecord

时间:2017-12-08 18:27:53      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:16px   生命周期   数据   mon   soft   model   sample   where   对象   

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]);

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、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   对象   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!