Yii2 数据库Active Record(ORM)
ACTIVE RECORD(ORM)
参考:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
- namespace app\models;
- use yii\db\ActiveRecord;
- class Customer extends ActiveRecord
- {
- const STATUS_ACTIVE = 'active';
- const STATUS_DELETED = 'deleted';
- public static function tableName()
- {
- return 'customer';
- }
- public static function getDb()
- {
- return \Yii::$app->db2; // use the "db2" application component
- }
- public static function init() //自定义初始默认数据
- {
- parent::init();
- $this->status = self::STATUS_ACTIVE;
- }
- }
访问数据列
- $id = $customer->id;
- $email = $customer->email;
- -------------
- $customer->email = 'jane@example.com';
- $customer->save();
查询数据
- $customers = Customer::find()
- ->where(['status' => Customer::STATUS_ACTIVE])
- ->orderBy('id')
- ->all();
- $customer = Customer::find()
- ->where(['id' => 1])
- ->one();
- $count = Customer::find()
- ->where(['status' => Customer::STATUS_ACTIVE])
- ->count();
- $customers = Customer::find()->indexBy('id')->all();
- $sql = 'SELECT * FROM customer';
- $customers = Customer::findBySql($sql)->all();
- // to return a single customer whose ID is 1:
- $customer = Customer::findOne(1);
- Customer::find()->where(['status' => Customer::STATUS_ACTIVE])->limit(1)->one()
- //返回数组
- $customers = Customer::find()
- ->asArray()
- ->all();
批量返回
- // fetch 10 customers at a time
- foreach (Customer::find()->batch(10) as $customers) {
- // $customers is an array of 10 or fewer Customer objects
- }
- // fetch 10 customers at a time and iterate them one by one
- foreach (Customer::find()->each(10) as $customer) {
- // $customer is a Customer object
- }
- // batch query with eager loading
- foreach (Customer::find()->with('orders')->each() as $customer) {
- }
数据处理
- save()
- insert()
- update()
- delete()
批量数据处理
- updateCounters()
- updateAll()
- updateAllCounters()
- deleteAll()
- // to insert a new customer record
- $customer = new Customer();
- $customer->name = 'James';
- $customer->email = 'james@example.com';
- $customer->save(); // equivalent to $customer->insert();
- // to update an existing customer record
- $customer = Customer::findOne($id);
- $customer->email = 'james@example.com';
- $customer->save(); // equivalent to $customer->update();
- // to delete an existing customer record
- $customer = Customer::findOne($id);
- $customer->delete();
- // to delete several customers
- Customer::deleteAll('age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']);
- // to increment the age of ALL customers by 1
- Customer::updateAllCounters(['age' => 1]);
数据效验
- $model = Customer::findOne($id);
- if ($model === null) {
- throw new NotFoundHttpException;
- }
- if ($model->load(Yii::$app->request->post()) && $model->save()) {
- // the user input has been collected, validated and saved
- }else{
- ;
- }
初始默认数据
- $customer = new Customer();
- $customer->loadDefaultValues();
生命与执行周期
初始化
- constructor
- init(): will trigger an EVENT_INIT event
调用 save()时
- beforeValidate(): //return bool
- afterValidate(): will trigger an EVENT_AFTER_VALIDATE event
- beforeSave(): will trigger an EVENT_BEFORE_INSERT or EVENT_BEFORE_UPDATE event
- perform the actual data insertion or updating
- afterSave(): will trigger an EVENT_AFTER_INSERT or EVENT_AFTER_UPDATE event
调用delete()删除时
- beforeDelete(): will trigger an EVENT_BEFORE_DELETE event
- perform the actual data deletion
- afterDelete(): will trigger an EVENT_AFTER_DELETE event
关联表数据
yii\db\ActiveRecord::hasMany() and yii\db\ActiveRecord::hasOne()
- class Customer extends \yii\db\ActiveRecord
- {
- public function getOrders()
- {
- // Customer has_many Order via Order.customer_id -> id
- return $this->hasMany(Order::className(), ['customer_id' => 'id']);
- }
- }
- class Order extends \yii\db\ActiveRecord
- {
- public function getCustomer()
- {
- // Order has_one Customer via Customer.id -> customer_id
- return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
- }
- }
- class Customer extends \yii\db\ActiveRecord
- {
- public function getBigOrders($threshold = 100)
- {
- return $this->hasMany(Order::className(), ['customer_id' => 'id'])
- ->where('subtotal > :threshold', [':threshold' => $threshold])
- ->orderBy('id');
- }
- }
- $orders = $customer->getBigOrders(200)->all();
中间关联表
via() or viaTable()
- class Order extends \yii\db\ActiveRecord
- {
- public function getItems()
- {
- return $this->hasMany(Item::className(), ['id' => 'item_id'])
- ->viaTable('order_item', ['order_id' => 'id']);
- }
- }
贪婪模式
- // SQL executed: SELECT * FROM customer WHERE id=1
- $customer = Customer::findOne(1);
- // SQL executed: SELECT * FROM order WHERE customer_id=1
- $orders = $customer->orders;
- // no SQL executed
- $orders2 = $customer->orders;
- ------------
- $customers = Customer::find()->limit(100)->all();
- foreach ($customers as $customer) {
- // SQL executed: SELECT * FROM order WHERE customer_id=...
- $orders = $customer->orders;
- // ...handle $orders...
- }
- ---------------
- // SQL executed: SELECT * FROM customer LIMIT 100;
- // SELECT * FROM orders WHERE customer_id IN (1,2,...)
- $customers = Customer::find()->limit(100)
- ->with('orders')->all();
- foreach ($customers as $customer) {
- // no SQL executed
- $orders = $customer->orders;
- // ...handle $orders...
- }
- -----------------------
- $customer = Customer::findOne(1);
- // lazy loading: SELECT * FROM order WHERE customer_id=1 AND subtotal>100
- $orders = $customer->getOrders()->where('subtotal>100')->all();
- // eager loading: SELECT * FROM customer LIMIT 100
- // SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100
- $customers = Customer::find()->limit(100)->with([
- 'orders' => function($query) {
- $query->andWhere('subtotal>100');
- },
- ])->all();
联合查询关联表
- // join with multiple relations
- // find the orders that contain books and were placed by customers who registered within the past 24 hours
- $orders = Order::find()->innerJoinWith([
- 'books',
- 'customer' => function ($query) {
- $query->where('customer.created_at > ' . (time() - 24 * 3600));
- }
- ])->all();
- // join with sub-relations: join with books and books' authors
- $orders = Order::find()->joinWith('books.author')->all();
- class User extends ActiveRecord
- {
- public function getBooks()
- {
- return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);
- }
- }
- // SELECT user.* FROM user LEFT JOIN item ON item.owner_id=user.id AND category_id=1
- // SELECT * FROM item WHERE owner_id IN (...) AND category_id=1
- $users = User::find()->joinWith('books')->all();
- // find all orders that contain books, but do not eager load "books".
- $orders = Order::find()->innerJoinWith('books', false)->all();
- // which is equivalent to the above
- $orders = Order::find()->joinWith('books', false, 'INNER JOIN')->all()
- //额外条件
- class User extends ActiveRecord
- {
- public function getBooks()
- {
- return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);
- }
- }
操作关系
link() and unlink()
- $customer = Customer::findOne(1);
- $order = new Order();
- $order->subtotal = 100;
- $customer->link('orders', $order);
- $customer->save();
Cross-DBMS
- // Relational database Active Record
- class Customer extends \yii\db\ActiveRecord
- {
- public static function tableName()
- {
- return 'customer';
- }
- public function getComments()
- {
- // Customer, stored in relational database, has many Comments, stored in MongoDB collection:
- return $this->hasMany(Comment::className(), ['customer_id' => 'id']);
- }
- }
- // MongoDb Active Record
- class Comment extends \yii\mongodb\ActiveRecord
- {
- public static function collectionName()
- {
- return 'comment';
- }
- public function getCustomer()
- {
- // Comment, stored in MongoDB collection, has one Customer, stored in relational database:
- return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
- }
- }
过滤
- namespace app\models;
- use yii\db\ActiveQuery;
- class CommentQuery extends ActiveQuery
- {
- public function active($state = true)
- {
- $this->andWhere(['active' => $state]);
- return $this;
- }
- }
- namespace app\models;
- use yii\db\ActiveRecord;
- class Comment extends ActiveRecord
- {
- /**
- * @inheritdoc
- * @return CommentQuery
- */
- public static function find()
- {
- return new CommentQuery(get_called_class());
- }
- }
- $comments = Comment::find()->active()->all();
- $inactiveComments = Comment::find()->active(false)->all();
- class Post extends \yii\db\ActiveRecord
- {
- public function getActiveComments()
- {
- return $this->hasMany(Comment::className(), ['post_id' => 'id'])->active();
- }
- }
- $posts = Post::find()->with([
- 'comments' => function($q) {
- $q->active();
- }
- ])->all();
- //默认
- public static function find()
- {
- return parent::find()->where(['deleted' => false]);
- }
事务
- class Post extends \yii\db\ActiveRecord
- {
- public function transactions()
- {
- return [
- 'admin' => self::OP_INSERT,
- 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
- // the above is equivalent to the following:
- // 'api' => self::OP_ALL,
- ];
- }
- }
- $model=Post::model();
- $transaction=$model->dbConnection->beginTransaction();
- try
- {
- // 查找和保存是可能由另一个请求干预的两个步骤
- // 这样我们使用一个事务以确保其一致性和完整性
- $post=$model->findByPk(10);
- $post->title='new post title';
- $post->save();
- $transaction->commit();
- }
- catch(Exception $e)
- {
- $transaction->rollBack();
- }
Yii2 数据库Active Record(ORM)的更多相关文章
- Yii2 三层设计模式:SQL Command、Query builder、Active Record(ORM)
用Yii2也有一段时间了,发现Yii2 Framework对Database的操作有非常良好的结构和弹性. 接下来介绍三种数据库操作方式. SQL Command Level: // Get DB c ...
- RoR - Introduction to Active Record
Active Record: ORM ( Object-relational Mapping)Bridges the gap between relational databases , which ...
- Android开源库--ActiveAndroid(active record模式的ORM数据库框架)
Github地址:https://github.com/pardom/ActiveAndroid 前言 我一般在Android开发中,几乎用不到SQLlite,因为一些小数据就直接使用Preferen ...
- DAL、DAO、ORM、Active Record辨析
转自:http://blog.csdn.net/suiye/article/details/7824943 模型 Model 模型是MVC中的概念,指的是读取数据和改变数据的操作(业务逻辑).一开始我 ...
- Active Record 数据库模式-增删改查操作
选择数据 下面的函数帮助你构建 SQL SELECT语句. 备注:如果你正在使用 PHP5,你可以在复杂情况下使用链式语法.本页面底部有具体描述. $this->db->get(); 运行 ...
- ORM Active Record Data Mapper
What's the difference between Active Record and Data Mapper? https://www.culttt.com/2014/06/18/whats ...
- Yii2 : Active Record add Not In condition
$query = MyModel::find()->where(['not in','attribute',$array]); 參考 Yii2 : Active Record add Not I ...
- Yii的学习(4)--Active Record
摘自Yii官网:http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.ar 在官网原文的基础上添加了CDbCriteria的详细用法. 虽然 ...
- Active Record快速入门指南
一.概述 Active Record(中文名:活动记录)是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一行记录.关系型数据库往往通过外键来表述实体关系,A ...
随机推荐
- 关于Linux_系统资源监控_dmesg_free_uptime_uname
(系统资源查看命令-dmesg[查看系统内核资源信息])->判断服务器的硬件状态 Comment:dmesg | grep CPU,指定查看cpu资源信息 (系统资源查看命令-free[查看内存 ...
- nodejs npm 常用配置
npm install moduleNames : 安装 Node 模块.node安装分为全局模式和本地模式. npm install -g moduleName.npm install expres ...
- 【leetcode】944. Delete Columns to Make Sorted
题目如下: We are given an array A of N lowercase letter strings, all of the same length. Now, we may cho ...
- Effective Objective-C 2.0
Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法 作者:Matt Galloway(英) 译者:爱飞翔 出版社:机械工业出版社 出版年:2014-01 ...
- webpack中的url-loader
使用url-loader引入图片,可以说它是file-loader的增强版 url-loader会把我们的图片使用base64的形式编码成另外一种字符串,网页是可以识别这种编码的东西的,这样的好处是, ...
- STM32 系统架构
这里所讲的 STM32 系统架构主要针对的 STM32F103 这些非互联型芯片 STM32 主系统主要由四个驱动单元和四个被动单元构成. 四个驱动单元是: 内核 DCode 总线; 系统总线;通用 ...
- 漫谈C语言结构体【转】
相信大家对于结构体都不陌生.在此,分享出本人对C语言结构体的学习心得.如果你发现这个总结中有你以前所未掌握的,那本文也算是有点价值了.当然,水平有限,若发现不足之处恳请指出.代码文件test.c我放在 ...
- python基础-包和模块
Python基础-包与模块 写在前面 如非特别说明,下文均基于Python3 摘要 为重用以及更好的维护代码,Python使用了模块与包:一个Python文件就是一个模块,包是组织模块的特殊目录(包含 ...
- Java-技术专区-问题专区-应该了解的基础技术点
Java基础 Arrays.sort实现原理和Collection实现原理 foreach和while的区别(编译之后) 线程池的种类,区别和使用场景 分析线程池的实现原理和线程的调度过程 线程池如何 ...
- SmartSql简介
0. Why 拥抱 跨平台 DotNet Core,是时候了. 高性能.高生产力,史上最轻量级的ORM.107kb 1. So SmartSql TargetFrameworks: .NETFrame ...