4

I've just checked the man page of CDbCriteria, but there is not enough info about it. This property is available since v1.1.7 and I couldn't find any help for it. Is it for dynamically changing Model->scopes "on-the-fly"?

stealthyninja
  • 10,343
  • 11
  • 51
  • 59
RusAlex
  • 8,245
  • 6
  • 36
  • 44
  • For anyone looking for examples, I created a [blog post](http://blog.4aal.nl/post/yii-named-scopes-examples) about this. – Henk Jun 04 '12 at 11:46

2 Answers2

14

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:

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

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). By returning the object itself you allow method chaining.

Here's an example:

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

Gets the last 3 items. Of course you can expand the example to almost any property in the database. Cheers

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93
  • but i have asked how to use CDbCriteria with scopes, not CActiveRecord scopes. and how to use them with params. – RusAlex Jun 30 '11 at 14:05
  • CActiveRecord scopes are actually affected by changes in CDbCriteria, and CDbCriteria scopes actually filter CActiveRecord records. CDbCriteria is a way to encapsulate the conditions for database results. So I don't find any difference. If you change your mind about it and see the big code block, that last() function is a custom scope with parameters. – Sergi Juanola Jun 30 '11 at 14:36
4

Yes, scopes can be used to change the attributes of CDbCriteria with pre-built conditions and can also be passed parameters. Before 1.1.7 you could use them in a model() query and can be chained together. See: 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. See: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes

ldg
  • 9,112
  • 2
  • 29
  • 44
  • can you show me examples of using ? i tryed myself, but i cant find a way to change parameters in the model scopes "on-the-fly" with criteria scopes property. – RusAlex Jun 30 '11 at 06:25