Yii2 数据库Active Record(ORM)

ACTIVE RECORD(ORM)

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

http://blog.csdn.net/hzqghost/article/details/44117745

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  




访问数据列

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $id = $customer->id;  
  2. $email = $customer->email;  
  3. -------------  
  4. $customer->email = 'jane@example.com';  
  5. $customer->save();  

查询数据

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. //返回数组  
  19. $customers = Customer::find()  
  20.     ->asArray()  
  21.     ->all();  

批量返回

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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()

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.   
  7.   
  8. // to update an existing customer record  
  9. $customer = Customer::findOne($id);  
  10. $customer->email = 'james@example.com';  
  11. $customer->save();  // equivalent to $customer->update();  
  12.   
  13. // to delete an existing customer record  
  14. $customer = Customer::findOne($id);  
  15. $customer->delete();  
  16.   
  17. // to delete several customers  
  18. Customer::deleteAll('age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']);  
  19.   
  20. // to increment the age of ALL customers by 1  
  21. Customer::updateAllCounters(['age' => 1]);  

数据效验

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  

初始默认数据

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $customer = new Customer();  
  2. $customer->loadDefaultValues();  

生命与执行周期

初始化

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. constructor  
  2. init(): will trigger an EVENT_INIT event  

调用 save()时

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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()删除时

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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() 

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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()

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  

贪婪模式

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.   
  10. foreach ($customers as $customer) {  
  11.     // SQL executed: SELECT * FROM order WHERE customer_id=...  
  12.     $orders = $customer->orders;  
  13.     // ...handle $orders...  
  14. }  
  15. ---------------  
  16. // SQL executed: SELECT * FROM customer LIMIT 100;  
  17. //               SELECT * FROM orders WHERE customer_id IN (1,2,...)  
  18. $customers = Customer::find()->limit(100)  
  19.     ->with('orders')->all();  
  20.   
  21. foreach ($customers as $customer) {  
  22.     // no SQL executed  
  23.     $orders = $customer->orders;  
  24.     // ...handle $orders...  
  25. }  
  26. -----------------------  
  27. $customer = Customer::findOne(1);  
  28. // lazy loading: SELECT * FROM order WHERE customer_id=1 AND subtotal>100  
  29. $orders = $customer->getOrders()->where('subtotal>100')->all();  
  30.   
  31. // eager loading: SELECT * FROM customer LIMIT 100  
  32. //                SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100  
  33. $customers = Customer::find()->limit(100)->with([  
  34.     'orders' => function($query) {  
  35.         $query->andWhere('subtotal>100');  
  36.     },  
  37. ])->all();  

联合查询关联表

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.   
  12. class User extends ActiveRecord  
  13. {  
  14.     public function getBooks()  
  15.     {  
  16.         return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);  
  17.     }  
  18. }  
  19. // SELECT user.* FROM user LEFT JOIN item ON item.owner_id=user.id AND category_id=1  
  20. // SELECT * FROM item WHERE owner_id IN (...) AND category_id=1  
  21. $users = User::find()->joinWith('books')->all();  
  22. // find all orders that contain books, but do not eager load "books".  
  23. $orders = Order::find()->innerJoinWith('books', false)->all();  
  24. // which is equivalent to the above  
  25. $orders = Order::find()->joinWith('books', false, 'INNER JOIN')->all()  
  26. //额外条件  
  27. class User extends ActiveRecord  
  28. {  
  29.     public function getBooks()  
  30.     {  
  31.         return $this->hasMany(Item::className(), ['owner_id' => 'id'])->onCondition(['category_id' => 1]);  
  32.     }  
  33. }  


操作关系
link() and unlink()
[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $customer = Customer::findOne(1);  
  2. $order = new Order();  
  3. $order->subtotal = 100;  
  4. $customer->link('orders'$order);  
  5. $customer->save();  

Cross-DBMS

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


过滤

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. namespace app\models;  
  2.   
  3. use yii\db\ActiveQuery;  
  4.   
  5. class CommentQuery extends ActiveQuery  
  6. {  
  7.     public function active($state = true)  
  8.     {  
  9.         $this->andWhere(['active' => $state]);  
  10.         return $this;  
  11.     }  
  12. }  
  13.   
  14. namespace app\models;  
  15.   
  16. use yii\db\ActiveRecord;  
  17.   
  18. class Comment extends ActiveRecord  
  19. {  
  20.     /** 
  21.      * @inheritdoc 
  22.      * @return CommentQuery 
  23.      */  
  24.     public static function find()  
  25.     {  
  26.         return new CommentQuery(get_called_class());  
  27.     }  
  28. }  
  29.   
  30. $comments = Comment::find()->active()->all();  
  31. $inactiveComments = Comment::find()->active(false)->all();  
  32.   
  33. class Post extends \yii\db\ActiveRecord  
  34. {  
  35.     public function getActiveComments()  
  36.     {  
  37.         return $this->hasMany(Comment::className(), ['post_id' => 'id'])->active();  
  38.   
  39.     }  
  40. }  
  41.   
  42. $posts = Post::find()->with([  
  43.     'comments' => function($q) {  
  44.         $q->active();  
  45.     }  
  46. ])->all();  
  47.   
  48. //默认  
  49. public static function find()  
  50. {  
  51.     return parent::find()->where(['deleted' => false]);  
  52. }  

事务

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  

[php]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值