Search code examples
yiirelational-databaseyii-cmodel

Browse Yii Relations with limits


I have a Community model and a Content model. Each Content has a community_id column. I created this simple relation:

$relations['contents'] = array(self::HAS_MANY, 'Content', 'community_id','order'=>'weight DESC, id DESC');

(note the ORDER)

In the CommunityController I want to display say the top 20 Contents (then in another ajax action get the next 20, no worries about that).

I could probably do it via Criteria, something like:

$criteria = new CDbCriteria;
$criteria->compare('community_id',$model->id);
$criteria->limit = 20;
$criteria->order = 'weight DESC, id DESC';
$contents = Content::model()->findAll($criteria);

But the code looks overkill to me (too long) and I feel like I'm not using at all the Relation I created. Is there a simpler way? Or am I looking for problems where there aren't?


Solution

  • You can use your relation as a method and pass criteria there:

    $contents = $model->contents(array('limit' => 20));