使用 Yii 框架的数据库特性
我最近开始使用 Yii PHP MVC 框架.我正在寻找关于如何通过框架继续使用数据库的建议:我应该使用框架的基类 CActiveRecord 来处理数据库,还是应该使用经典的 SQL 查询函数(在我的例子中是 mssql)?
I recently started working with Yii PHP MVC Framework. I'm looking for advice on how should I continue working with the database through the framework: should I use framework's base class CActiveRecord which deals with the DB, or should I go with the classic SQL query functions (in my case mssql)?
显然与否,对我来说,通过经典 SQL 查询处理数据库似乎更容易,但是,在某些时候,我认为使用框架的方式必须具有优势.一些 SQL 查询经常会变得非常复杂.我只是无法理解该框架如何帮助我并且不会让事情变得比实际情况更复杂.
Obviously or not, for me it seems easier to deal with the DB through classic SQL queries, but, at some point, I imagine there has to be an advantage in using framework's way. Some SQL queries will get pretty complex pretty often. I just can't comprehend how the framework could help me and not make things more complicated than they actually are.
推荐答案
我在 Yii 和海量数据库方面的经验的非常一般的规则:
Very General rule from my experience with Yii and massive databases:
在以下情况下使用 Yii Active Record:
- 您想在数据库中检索单个行并将其发布到几行(例如,用户更改他/她的设置、更新用户余额、添加投票、获取在线用户数、获取某个主题下的帖子数、检查模型是否存在)
- 您希望在表格之间快速设计分层模型结构(例如 $user->info->email、$user->settings->currency),以便您可以快速调整每次使用时显示的货币/设置.莉>
在以下情况下远离 Yii Active Record:
您想一次更新 100 条记录.(模型开销太大)
You want to update several 100 records at a time. (too much overhead for the model)
Yii::app()->db->command()
允许您避开重物并以简单数组检索数据.
allows you to avoid the heavy objects and retrieves data in simple arrays.
您想要进行涉及多个表的高级联接和查询.
You want to do advanced joins and queries that involve multiple tables.
任何批处理作业!!(例如,检查付款表以了解哪些客户逾期付款、更新数据库值等)
Any batch job!! (e.g. checking a payments table to see which customers are overdue on their payments, updating database values etc.)
我喜欢 Yii Active Record,但我会根据应用程序的需求在 Active Record 模型和普通 SQL(使用 Yii::app()->db)之间互换.
I love Yii Active Record, but I interchange between the Active Record Model and plain SQL (using Yii::app()->db) based on the requirement in the application.
最后我可以选择是否要更新单个用户的货币
At the end I have the option whether I want to update a single users currency
$user->info->currency = 'USD';
$user->info->save();
或者如果我想更新所有用户的货币:
or if I want to update all users currencies:
Yii::app()->db->command('UPDATE ..... SET Currency="USD" where ...');
相关文章