Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created February 25, 2014 05:53
Show Gist options
  • Save umidjons/9203479 to your computer and use it in GitHub Desktop.
Save umidjons/9203479 to your computer and use it in GitHub Desktop.
Yii: Named and parameterized scopes example
<?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