简体   繁体   English

谁能解释 CDbCriteria->scopes 是如何工作的?

[英]Can anyone explain how CDbCriteria->scopes works?

I've just checked the man page of CDbCriteria , but there is not enough info about it.我刚刚检查了CDbCriteria的手册页,但没有足够的信息。 This property is available since v1.1.7 and I couldn't find any help for it.这个属性从 v1.1.7 开始可用,我找不到任何帮助。 Is it for dynamically changing Model->scopes "on-the-fly"?是否用于动态更改Model->scopes “动态”?

Scopes are an easy way to create simple filters by default.默认情况下,范围是创建简单过滤器的一种简单方法。 With a scope you can sort your results by specific columns automatically, limit the results, apply conditions, etc. In the links provided by @ldg there's a big example of how cool they are:使用 scope,您可以按特定列自动对结果进行排序、限制结果、应用条件等。在@ldg 提供的链接中,有一个很好的例子来说明它们有多酷:

$posts=Post::model()->published()->recently()->findAll();

Somebody is retrieving all the recently published posts in one single line.有人正在一行中检索所有最近发布的帖子。 They are easier to maintain than inline conditions (for example Post::model()->findAll('status=1') ) and are encapsulated inside each model, which means big transparency and ease of use.它们比内联条件(例如Post::model()->findAll('status=1') )更易于维护,并且被封装在每个 model 中,这意味着高透明度和易用性。

Plus, you can create your own parameter based scopes like this:另外,您可以创建自己的基于参数的范围,如下所示:

public function last($amount)
{
    $this->getDbCriteria()->mergeWith(array(
        'order' => 't.create_time DESC',
        'limit' => $amount,
    ));
    return $this;
}

Adding something like this into a Model will let you choose the amount of objects you want to retrieve from the database (sorted by its create time).将这样的内容添加到 Model 将让您选择要从数据库中检索的对象数量(按其创建时间排序)。 By returning the object itself you allow method chaining.通过返回 object 本身,您可以允许方法链接。

Here's an example:这是一个例子:

$last3posts=Post::model()->last(3)->findAll();

Gets the last 3 items.获取最后 3 个项目。 Of course you can expand the example to almost any property in the database.当然,您可以将示例扩展到数据库中的几乎任何属性。 Cheers干杯

Yes, scopes can be used to change the attributes of CDbCriteria with pre-built conditions and can also be passed parameters.是的,范围可以用来改变带有预建条件的 CDbCriteria 的属性,也可以传递参数。 Before 1.1.7 you could use them in a model() query and can be chained together.在 1.1.7 之前,您可以在 model() 查询中使用它们并且可以链接在一起。 See: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes见: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

Since 1.1.7, you can also use scopes as a CDbCriteria property.从 1.1.7 开始,您还可以将范围用作 CDbCriteria 属性。 See: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes参见: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM