简单的故事。我有用户和博客帖子,用户与博客帖子有关,分为ONE到MANY。我想向用户展示他们的个人资料以及他们撰写的5篇最新帖子:
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'posts' => array(self::HAS_MANY, 'BlogPost', 'userId')
);
}
我正在尝试应用限制:
$user = User::model()->with(array(
'posts' => array('order' => 'updatedAt DESC'),
->findAll(array(
'condition' => 'userId = :userId AND ...',
'params' => array(
'userId' => $userId
),
'limit' => 5
));
但是Yii框架忽略了这一点。我怎么能完成它?
这是Yii 1.1。
答案 0 :(得分:0)
您必须在with
:
$user = User::model()
->with(array(
'posts' => array(
'order' => 'updatedAt DESC',
'limit' => 5
)
))->findAll(array(
'condition' => 'userId = :userId AND ...',
'params' => array(
'userId' => $userId
),
));
答案 1 :(得分:0)
relations()函数应该如下所示:
return array(
'posts' => array(self::HAS_MANY, 'BlogPost', 'userId'),
'recentPosts' => array(self::HAS_MANY, 'BlogPost', 'userId',
'order' => 'updatedAt DESC',
'limit' => 5
)
);
致电$user->posts
您将获得所有帖子,致电$user->recentPosts
只会获得最后5个。