ActiveRecord (CDbCriteria) vs QueryBuilder?

混江龙づ霸主 提交于 2019-12-10 10:24:14

问题


I have to make some filters, such as get persons who are in a given department, and I was wondering about the best way to do it.

Some of them are going to require the join of multiple tables.

Does anyone know about the main differences between CDbCriteria and Query Builder? I would particularly like to know about the compatibility with databases.

I found this in the Yii documentation about Query Builder:

It offers certain degree of DB abstraction, which simplifies migration to different DB platforms.

Is it the same for the CDbCriteria objects? Is it better?


回答1:


The concept of CDbCriteria is used when working with Yii's active record (AR) abstraction (which is usually all of the time). AR requires that you have created models for the various tables in your database.

Query builder a very different way to access the database; in effect it is a structured wrapper that allows you to programmatically construct an SQL query instead of just writing it out as a string (as an added bonus it also offers a degree of database abstraction as you mention).

In a typical application there would be little to no need to use query builder because AR already provides a great deal of functionality and it also offers the same degree of database abstraction.

In some cases you might want to run a very specific type of query that is not convenient or performant to issue through AR. You then have two options:

  1. If the query is fixed or almost fixed then you can simply issue it through DAO; in fact the query builder documentation mentions that "if your queries are simple, it is easier and faster to directly write SQL statements".
  2. If the query needs to be dynamically constructed then query builder becomes a good fit for the job.

So as you can see, query builder is not all that useful most of the time. Only if you want to write very customized and at the same time dynamically constructed queries does it make sense to use it.

The example feature that you mention can and should be implemented using AR.



来源:https://stackoverflow.com/questions/14299029/activerecord-cdbcriteria-vs-querybuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!