ACTIVE RECORD(ORM)

参考:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

  1. namespace app\models;
  2. use yii\db\ActiveRecord;
  3. class Customer extends ActiveRecord
  4. {
  5. const STATUS_ACTIVE = 'active';
  6. const STATUS_DELETED = 'deleted';
  7. public static function tableName()
  8. {
  9. return 'customer';
  10. }
  11. public static function getDb()
  12. {
  13. return \Yii::$app->db2;  // use the "db2" application component
  14. }
  15. public static function init() //自定义初始默认数据
  16. {
  17. parent::init();
  18. $this->status = self::STATUS_ACTIVE;
  19. }
  20. }

访问数据列

  1. $id = $customer->id;
  2. $email = $customer->email;
  3. -------------
  4. $customer->email = 'jane@example.com';
  5. $customer->save();


查询数据

  1. $customers = Customer::find()
  2. ->where(['status' => Customer::STATUS_ACTIVE])
  3. ->orderBy('id')
  4. ->all();
  5. $customer = Customer::find()
  6. ->where(['id' => 1])
  7. ->one();
  8. $count = Customer::find()
  9. ->where(['status' => Customer::STATUS_ACTIVE])
  10. ->count();
  11. $customers = Customer::find()->indexBy('id')->all();
  12. $sql = 'SELECT * FROM customer';
  13. $customers = Customer::findBySql($sql)->all();
  14. // to return a single customer whose ID is 1:
  15. $customer = Customer::findOne(1);
  16. Customer::find()->where(['status' => Customer::STATUS_ACTIVE])->limit(1)->one()
  17. //返回数组
  18. $customers = Customer::find()
  19. ->asArray()
  20. ->all();


批量返回

  1. // fetch 10 customers at a time
  2. foreach (Customer::find()->batch(10) as $customers) {
  3. // $customers is an array of 10 or fewer Customer objects
  4. }
  5. // fetch 10 customers at a time and iterate them one by one
  6. foreach (Customer::find()->each(10) as $customer) {
  7. // $customer is a Customer object
  8. }
  9. // batch query with eager loading
  10. foreach (Customer::find()->with('orders')->each() as $customer) {
  11. }

数据处理

  • save()
  • insert()
  • update()
  • delete()

批量数据处理

  • updateCounters()
  • updateAll()
  • updateAllCounters()
  • deleteAll()
  1. // to insert a new customer record
  2. $customer = new Customer();
  3. $customer->name = 'James';
  4. $customer->email = 'james@example.com';
  5. $customer->save();  // equivalent to $customer->insert();
  6. // to update an existing customer record
  7. $customer = Customer::findOne($id);
  8. $customer->email = 'james@example.com';
  9. $customer->save();  // equivalent to $customer->update();
  10. // to delete an existing customer record
  11. $customer = Customer::findOne($id);
  12. $customer->delete();
  13. // to delete several customers
  14. Customer::deleteAll('age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']);
  15. // to increment the age of ALL customers by 1
  16. Customer::updateAllCounters(['age' => 1]);

数据效验

  1. $model = Customer::findOne($id);
  2. if ($model === null) {
  3. throw new NotFoundHttpException;
  4. }
  5. if ($model->load(Yii::$app->request->post()) && $model->save()) {
  6. // the user input has been collected, validated and saved
  7. }else{
  8. ;
  9. }

初始默认数据

  1. $customer = new Customer();
  2. $customer->loadDefaultValues();

生命与执行周期

初始化

  1. constructor
  2. init(): will trigger an EVENT_INIT event

调用 save()时

  1. beforeValidate(): //return bool
  2. afterValidate(): will trigger an EVENT_AFTER_VALIDATE event
  3. beforeSave(): will trigger an EVENT_BEFORE_INSERT or EVENT_BEFORE_UPDATE event
  4. perform the actual data insertion or updating
  5. afterSave(): will trigger an EVENT_AFTER_INSERT or EVENT_AFTER_UPDATE event

调用delete()删除时

  1. beforeDelete(): will trigger an EVENT_BEFORE_DELETE event
  2. perform the actual data deletion
  3. afterDelete(): will trigger an EVENT_AFTER_DELETE event

关联表数据

yii\db\ActiveRecord::hasMany() and yii\db\ActiveRecord::hasOne()

  1. class Customer extends \yii\db\ActiveRecord
  2. {
  3. public function getOrders()
  4. {
  5. // Customer has_many Order via Order.customer_id -> id
  6. return $this->hasMany(Order::className(), ['customer_id' => 'id']);
  7. }
  8. }
  9. class Order extends \yii\db\ActiveRecord
  10. {
  11. public function getCustomer()
  12. {
  13. // Order has_one Customer via Customer.id -> customer_id
  14. return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
  15. }
  16. }
  17. class Customer extends \yii\db\ActiveRecord
  18. {
  19. public function getBigOrders($threshold = 100)
  20. {
  21. return $this->hasMany(Order::className(), ['customer_id' => 'id'])
  22. ->where('subtotal > :threshold', [':threshold' => $threshold])
  23. ->orderBy('id');
  24. }
  25. }
  26. $orders = $customer->getBigOrders(200)->all();

中间关联表
via() or viaTable()

  1. class Order extends \yii\db\ActiveRecord
  2. {
  3. public function getItems()
  4. {
  5. return $this->hasMany(Item::className(), ['id' => 'item_id'])
  6. ->viaTable('order_item', ['order_id' => 'id']);
  7. }
  8. }

贪婪模式

  1. // SQL executed: SELECT * FROM customer WHERE id=1
  2. $customer = Customer::findOne(1);
  3. // SQL executed: SELECT * FROM order WHERE customer_id=1
  4. $orders = $customer->orders;
  5. // no SQL executed
  6. $orders2 = $customer->orders;
  7. ------------
  8. $customers = Customer::find()->limit(100)->all();
  9. foreach ($customers as $customer) {
  10. // SQL executed: SELECT * FROM order WHERE customer_id=...
  11. $orders = $customer->orders;
  12. // ...handle $orders...
  13. }
  14. ---------------
  15. // SQL executed: SELECT * FROM customer LIMIT 100;
  16. //               SELECT * FROM orders WHERE customer_id IN (1,2,...)
  17. $customers = Customer::find()->limit(100)
  18. ->with('orders')->all();
  19. foreach ($customers as $customer) {
  20. // no SQL executed
  21. $orders = $customer->orders;
  22. // ...handle $orders...
  23. }
  24. -----------------------
  25. $customer = Customer::findOne(1);
  26. // lazy loading: SELECT * FROM order WHERE customer_id=1 AND subtotal>100
  27. $orders = $customer->getOrders()->where('subtotal>100')->all();
  28. // eager loading: SELECT * FROM customer LIMIT 100
  29. //                SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100
  30. $customers = Customer::find()->limit(100)->with([
  31. 'orders' => function($query) {
  32. $query->andWhere('subtotal>100');
  33. },
  34. ])->all();

联合查询关联表

  1. // join with multiple relations
  2. // find the orders that contain books and were placed by customers who registered within the past 24 hours
  3. $orders = Order::find()->innerJoinWith([
  4. 'books',
  5. 'customer' => function ($query) {
  6. $query->where('customer.created_at > ' . (time() - 24 * 3600));
  7. }
  8. ])->all();
  9. // join with sub-relations: join with books and books' authors
  10. $orders = Order::find()->joinWith('books.author')->all();
  11. class User extends ActiveRecord
  12. {
  13. public function getBooks()
  14. {
  15. return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);
  16. }
  17. }
  18. // SELECT user.* FROM user LEFT JOIN item ON item.owner_id=user.id AND category_id=1
  19. // SELECT * FROM item WHERE owner_id IN (...) AND category_id=1
  20. $users = User::find()->joinWith('books')->all();
  21. // find all orders that contain books, but do not eager load "books".
  22. $orders = Order::find()->innerJoinWith('books', false)->all();
  23. // which is equivalent to the above
  24. $orders = Order::find()->joinWith('books', false, 'INNER JOIN')->all()
  25. //额外条件
  26. class User extends ActiveRecord
  27. {
  28. public function getBooks()
  29. {
  30. return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);
  31. }
  32. }

操作关系
link() and unlink()

  1. $customer = Customer::findOne(1);
  2. $order = new Order();
  3. $order->subtotal = 100;
  4. $customer->link('orders', $order);
  5. $customer->save();


Cross-DBMS

  1. // Relational database Active Record
  2. class Customer extends \yii\db\ActiveRecord
  3. {
  4. public static function tableName()
  5. {
  6. return 'customer';
  7. }
  8. public function getComments()
  9. {
  10. // Customer, stored in relational database, has many Comments, stored in MongoDB collection:
  11. return $this->hasMany(Comment::className(), ['customer_id' => 'id']);
  12. }
  13. }
  14. // MongoDb Active Record
  15. class Comment extends \yii\mongodb\ActiveRecord
  16. {
  17. public static function collectionName()
  18. {
  19. return 'comment';
  20. }
  21. public function getCustomer()
  22. {
  23. // Comment, stored in MongoDB collection, has one Customer, stored in relational database:
  24. return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
  25. }
  26. }


过滤

  1. namespace app\models;
  2. use yii\db\ActiveQuery;
  3. class CommentQuery extends ActiveQuery
  4. {
  5. public function active($state = true)
  6. {
  7. $this->andWhere(['active' => $state]);
  8. return $this;
  9. }
  10. }
  11. namespace app\models;
  12. use yii\db\ActiveRecord;
  13. class Comment extends ActiveRecord
  14. {
  15. /**
  16. * @inheritdoc
  17. * @return CommentQuery
  18. */
  19. public static function find()
  20. {
  21. return new CommentQuery(get_called_class());
  22. }
  23. }
  24. $comments = Comment::find()->active()->all();
  25. $inactiveComments = Comment::find()->active(false)->all();
  26. class Post extends \yii\db\ActiveRecord
  27. {
  28. public function getActiveComments()
  29. {
  30. return $this->hasMany(Comment::className(), ['post_id' => 'id'])->active();
  31. }
  32. }
  33. $posts = Post::find()->with([
  34. 'comments' => function($q) {
  35. $q->active();
  36. }
  37. ])->all();
  38. //默认
  39. public static function find()
  40. {
  41. return parent::find()->where(['deleted' => false]);
  42. }

事务

  1. class Post extends \yii\db\ActiveRecord
  2. {
  3. public function transactions()
  4. {
  5. return [
  6. 'admin' => self::OP_INSERT,
  7. 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
  8. // the above is equivalent to the following:
  9. // 'api' => self::OP_ALL,
  10. ];
  11. }
  12. }
    1. $model=Post::model();
    2. $transaction=$model->dbConnection->beginTransaction();
    3. try
    4. {
    5. // 查找和保存是可能由另一个请求干预的两个步骤
    6. // 这样我们使用一个事务以确保其一致性和完整性
    7. $post=$model->findByPk(10);
    8. $post->title='new post title';
    9. $post->save();
    10. $transaction->commit();
    11. }
    12. catch(Exception $e)
    13. {
    14. $transaction->rollBack();
    15. }

Yii2 数据库Active Record(ORM)的更多相关文章

  1. Yii2 三层设计模式:SQL Command、Query builder、Active Record(ORM)

    用Yii2也有一段时间了,发现Yii2 Framework对Database的操作有非常良好的结构和弹性. 接下来介绍三种数据库操作方式. SQL Command Level: // Get DB c ...

  2. RoR - Introduction to Active Record

    Active Record: ORM ( Object-relational Mapping)Bridges the gap between relational databases , which ...

  3. Android开源库--ActiveAndroid(active record模式的ORM数据库框架)

    Github地址:https://github.com/pardom/ActiveAndroid 前言 我一般在Android开发中,几乎用不到SQLlite,因为一些小数据就直接使用Preferen ...

  4. DAL、DAO、ORM、Active Record辨析

    转自:http://blog.csdn.net/suiye/article/details/7824943 模型 Model 模型是MVC中的概念,指的是读取数据和改变数据的操作(业务逻辑).一开始我 ...

  5. Active Record 数据库模式-增删改查操作

    选择数据 下面的函数帮助你构建 SQL SELECT语句. 备注:如果你正在使用 PHP5,你可以在复杂情况下使用链式语法.本页面底部有具体描述. $this->db->get(); 运行 ...

  6. ORM Active Record Data Mapper

    What's the difference between Active Record and Data Mapper? https://www.culttt.com/2014/06/18/whats ...

  7. Yii2 : Active Record add Not In condition

    $query = MyModel::find()->where(['not in','attribute',$array]); 參考 Yii2 : Active Record add Not I ...

  8. Yii的学习(4)--Active Record

    摘自Yii官网:http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.ar 在官网原文的基础上添加了CDbCriteria的详细用法. 虽然 ...

  9. Active Record快速入门指南

    一.概述 Active Record(中文名:活动记录)是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一行记录.关系型数据库往往通过外键来表述实体关系,A ...

随机推荐

  1. MariaDB 安装

    MariaDB的所有下载都位于官方MariaDB基金会网站的下载部分. 单击所需版本的链接,并显示多个操作系统,体系结构和安装文件类型的下载列表. 在LINUX / UNIX上安装 如果你熟悉Linu ...

  2. POJ 1321 棋盘问题(dfs入门)

    Description 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子 ...

  3. 学习.net的步骤

    第一步 学习HTML与CSS 这并不需要去学一大堆的诸如Dreamweaver,Firework之类的各种网页设计工具,关键是理解HTML网页嵌套的block结构与CSS的box模型.许多ASP.NE ...

  4. sql中简单的触发器功能

    触发器分为DML触发器和DDL触发器DML触发器包含After触发器,执行insert update delete语句后会触发after触发器,会事务回滚DML触发器还包含instead of触发器, ...

  5. c++ 获取文件图标,类型名称,属性 SHGetFileInfo

    SHGetFileInfo是一个相当实用的Windows API函数. // [MoreWindows工作笔记4] 获取文件图标,类型名称,属性 SHGetFileInfo #include < ...

  6. 探索Redis设计与实现4:Redis内部数据结构详解——ziplist

    本文转自互联网 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial ...

  7. SQL执行计划详解explain

    1.使用explain语句去查看分析结果 如explain select * from test1 where id=1;会出现:id selecttype table type possible_k ...

  8. sql审核工具调研安装-sqlAdvisor和soar

    sql审核工具调研  基于soar的sql审核查询平台: https://github.com/beiketianzhuang/data-platform-soar 1.美团工具sqlAdvisor工 ...

  9. windows下Docker安装MySQL

    # docker 中下载 mysql docker pull mysql #启动 docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD ...

  10. python学习笔记:通配符之glob模块(过滤)

    glob模块用来查找文件目录和文件,可以和常用的find功能进行类比.glob支持*?[]这三种通配符.返回的数据类型是list.常见的两个方法有glob.glob()和glob.iglob(),ig ...