Arman P.
Arman P.

Reputation: 4394

Yii limit on related model while querying

I ran into limit problem. The code that I'm using is the following:

$model = PostCategory::model();
  $record = $model->with(array(
    'posts'=>array(
      'order'=>'posts.createTime DESC',
      'limit'=>3,
))->findByPK($id);

I want to limit the posts queried for paging purposes. I've also tried to add

'together'=>true

after limit, this doesn't help too.

Any help is appreciated.

Upvotes: 5

Views: 6732

Answers (3)

Gerhard Liebenberg
Gerhard Liebenberg

Reputation: 444

Here is a wiki on parameterized named scopes.

But if you want to filter records in RELATED tables while using Relational Query, then you should use defaultScope().

Here is a wiki on defaultScope and it also shows how to bypass defaultScope when it is not needed.

Upvotes: 1

bool.dev
bool.dev

Reputation: 17478

This will definitely work, just tested :

$model = PostCategory::model();
$record = $model->with(array(
  'posts'=>array(
     'order'=>'posts.createTime DESC',
  ))->findByPK($id,
             array('limit'=>3,'together'=>true) // adding this works
);

Upvotes: 5

briiC
briiC

Reputation: 2134

You could add scope in your Post model and use

PostModel.php

public function recent( $limit = 3 ) {

    $this->getDbCriteria()->mergeWith(array(
        'order' => $this->getTableAlias(false, false).'.createTime DESC',
        'limit' => (int) $limit,
    ));

    return $this;
}

MyController.php

$record = $model->with('posts:recent')->findByPK($id);

And you have clean and readable code.

See more info about scopes http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

And this forum post how to give params to your scope using ->with http://www.yiiframework.com/forum/index.php/topic/23358-parameterized-vs-named-scopes-question-using-yii-118/

Upvotes: 0

Related Questions