torsdag den 17. oktober 2013

Yii Magic, Use of Scope

Hi,

This is one the magical features of ActiveRecord (AR) in Yii Framework.

When you need to create a Scope or limitation, the only thing that needs to be done is to define and add the 'function scopes' in the model class and then you are able to define the Scope rules.

Example:

In this example the 'owner' scope is defined. If you are familiar with the CDBCriteria definitions, defining the Scope would be like a `walk in the park`.

public function scopes()
    {
        return array(
            'owner'=>array(
                'with'=>array('department'),               
                'condition'=>'t.department_id = department.id AND department.user_company_id=:user_company_id',
                'params'=>array(
                    ':user_company_id'=>Ccom::user()->userCompany->id,
                ),
            ),
        );
     }

/**
* Ccom::user()->userCompany->id 
* is my short hand for
* User::model()->findByPk(Yii::app()->user->id)->userCompany->id
*/

This rule is defined so the user can only access her or his own groups in the departments of his company.

't.' in this case is the Group table, and Group table is related to Department table by the foreign key 'department_id' and Department is related to the UserCompany table by the foreign key 'user_company_id'

To use this Scope you have many options.

Examples:
Use
$dataProvider=new CActiveDataProvider(Group::model()->owner());
Instead of
$dataProvider=new CActiveDataProvider('Group');

Group::model()->owner() return a type CDbCritera object, with every thing there is needed to make an approperiate Select from the database

Use
Department::model()->owner()->findAll();
Instead of
Department::model()->findAll();

Use
$model->owner()->search();
Instead of
$model->search();

I wish the Yii Core developers best of luck. They really do a great job.
Please leave a comment or link if you have related knowledge about this subject, thanks.

Read more here: http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

Ingen kommentarer:

Send en kommentar