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. c# 泛型的抗变和协变

    namespace test { // 泛型的协变,T 只能作为返回的参数 public interface Class1<out T> { T Get(); int Count { ge ...

  2. 【LeetCode 36】有效的数独

    题目链接 [题解] 就一傻逼模拟题 [代码] class Solution { public: bool isValidSudoku(vector<vector<char>>& ...

  3. 容器————priority_queue

    #include <queue> 与queue不同的是可以自定义其中数据的优先级,让优先级高的先出队列. 优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本 ...

  4. paper 143:人脸验证

    持续更新ing,敬请期待! 参考:http://blog.csdn.net/stdcoutzyx/article/details/42091205  1. DeepID人脸识别算法 香港中文大学的团队 ...

  5. 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: ...

  6. IDEA入门使用--二

    *)IDEA安装和破解:https://www.cnblogs.com/jajian/p/7989032.html    这次我安装的是最新版2019的IDEA *)导入项目时,根据提示,一步步来.其 ...

  7. mysql数据权限操作

    1.创建新用户 通过root用户登录之后创建 >> grant all privileges on *.* to testuser@localhost identified by &quo ...

  8. Windows下 wamp下Apache配置虚拟域名

    安装好wamp后  找到 找到  Include conf/extra/httpd-vhosts.conf   去掉前面的#   并保存 修改 DocumentRoot  和  ServerName ...

  9. shell 字符串匹配变量(只取数字或者取固定字符串)

    var1=abc3559   #想要获得3559 操作: var1_key=`echo $var1 | tr -cd "[0-9]"` https://www.cnblogs.co ...

  10. shell编程:有类型的变量

    1.通过 declare 和 typeset 命令 declare 和 typeset 两者等价 declare 和 typeset 都是用来定义变量类型的 下面以 declare 进行总结 2.de ...