ActiveRecord (CDbCriteria) 与 QueryBuilder? [英] ActiveRecord (CDbCriteria) vs QueryBuilder?

查看:21
本文介绍了ActiveRecord (CDbCriteria) 与 QueryBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须制作一些过滤器,例如获取特定部门的人员,我想知道这样做的最佳方法.

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.

有人知道CDbCriteria 和查询生成器之间的主要区别吗?我特别想知道数据库的兼容性.

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

我在关于查询生成器的 Yii 文档中找到了这个:

I found this in the Yii documentation about Query Builder:

它提供了一定程度的数据库抽象,简化了到不同数据库平台的迁移.

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

CDbCriteria 对象是否相同?更好吗?

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

推荐答案

CDbCriteria 的概念是在使用 Yii 的 活动记录 (AR) 抽象(通常是所有时间).AR 要求您已经创建了模型用于数据库中的各种表.

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.

查询构建器 一种非常不同的访问方式数据库;实际上,它是一个结构化的包装器,允许您以编程方式构建 SQL 查询,而不仅仅是将其写为字符串(作为额外的好处,它还提供了一定程度的数据库抽象,正如您所提到的).

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).

在典型的应用程序中,几乎不需要使用查询构建器,因为 AR 已经提供了大量功能,并且还提供了相同程度的数据库抽象.

在某些情况下,您可能希望运行一种非常特定类型的查询,但通过 AR 发出的查询不方便或不高效.然后你有两个选择:

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. 如果查询是固定的或几乎固定的,那么您可以简单地通过 DAO;事实上,查询构建器文档提到如果您的查询很简单,直接编写 SQL 语句会更容易、更快".
  2. 如果需要动态构建查询,那么查询构建器就非常适合这项工作.
  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.

您提到的示例功能可以而且应该使用 AR 实现.

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

这篇关于ActiveRecord (CDbCriteria) 与 QueryBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆