2

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Nathan H
  • 48,033
  • 60
  • 165
  • 247

2 Answers2

1

You can use CActiveRecord::getRelated() and add your new criteria as the last parameter. Your code might look something like

$criteria = new CDbCriteria;
$criteria->limit = 20;
$contents=$model->getRelated('contents',true,$criteria);
topher
  • 14,790
  • 7
  • 54
  • 70
1

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

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