Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain how CDbCriteria->scopes works?

Tags:

yii

cdb

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"?

like image 715
RusAlex Avatar asked Dec 03 '22 02:12

RusAlex


2 Answers

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

like image 73
Sergi Juanola Avatar answered Jan 10 '23 15:01

Sergi Juanola


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

like image 43
ldg Avatar answered Jan 10 '23 13:01

ldg