Created
February 25, 2014 05:53
-
-
Save umidjons/9203479 to your computer and use it in GitHub Desktop.
Yii: Named and parameterized scopes example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This is the model class for table "news_comments". | |
* | |
* The followings are the available columns in table 'news_comments': | |
* @property string $id | |
* @property integer $news_id | |
* @property string $author | |
* @property string $text | |
* @property integer $status | |
* @property string $created_at | |
* @property string $updated_at | |
*/ | |
class NewsComments extends CActiveRecord | |
{ | |
// ... | |
public function scopes() | |
{ | |
return [ | |
'approved' => [ | |
'condition' => 'status=1', | |
'order' => 'created_at', | |
], | |
]; | |
} | |
public function belongingToNews( $news_id ) | |
{ | |
$this->getDbCriteria()->mergeWith( [ | |
'condition' => 'news_id=:news_id', | |
'params' => [ ':news_id' => $news_id ], | |
] ); | |
return $this; | |
} | |
// ... | |
} | |
// usage: | |
$news = News::model()->findByPk( 23 ); // get news model by id | |
$comments = NewsComments::model()->approved()->belongingToNews( $news->id )->findAll(); // get all approved comment models for this news model |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment