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 ...
随机推荐
- c# 泛型的抗变和协变
namespace test { // 泛型的协变,T 只能作为返回的参数 public interface Class1<out T> { T Get(); int Count { ge ...
- 【LeetCode 36】有效的数独
题目链接 [题解] 就一傻逼模拟题 [代码] class Solution { public: bool isValidSudoku(vector<vector<char>>& ...
- 容器————priority_queue
#include <queue> 与queue不同的是可以自定义其中数据的优先级,让优先级高的先出队列. 优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本 ...
- paper 143:人脸验证
持续更新ing,敬请期待! 参考:http://blog.csdn.net/stdcoutzyx/article/details/42091205 1. DeepID人脸识别算法 香港中文大学的团队 ...
- mapreduce求共同好友
逻辑分析 以下是qq的好友列表数据,冒号前是一个用户,冒号后是该用户的所有好友(数据中的好友关系是单向的) A:B,C,D,F,E,O B:A,C,E,K C:F,A,D,I D:A,E,F,L E: ...
- IDEA入门使用--二
*)IDEA安装和破解:https://www.cnblogs.com/jajian/p/7989032.html 这次我安装的是最新版2019的IDEA *)导入项目时,根据提示,一步步来.其 ...
- mysql数据权限操作
1.创建新用户 通过root用户登录之后创建 >> grant all privileges on *.* to testuser@localhost identified by &quo ...
- Windows下 wamp下Apache配置虚拟域名
安装好wamp后 找到 找到 Include conf/extra/httpd-vhosts.conf 去掉前面的# 并保存 修改 DocumentRoot 和 ServerName ...
- shell 字符串匹配变量(只取数字或者取固定字符串)
var1=abc3559 #想要获得3559 操作: var1_key=`echo $var1 | tr -cd "[0-9]"` https://www.cnblogs.co ...
- shell编程:有类型的变量
1.通过 declare 和 typeset 命令 declare 和 typeset 两者等价 declare 和 typeset 都是用来定义变量类型的 下面以 declare 进行总结 2.de ...