2016-11-30 35 views
0

簡單的故事。我有用戶和博客帖子,用戶與博客帖子相關爲ONE to MANY。我想向用戶展示了5所最近發表的文章中寫道,他們沿着他們的個人資料:Yii:限制HAS_MANY關係

/** 
    * @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

你必須包括在with極限:

$user = User::model() 
    ->with(array(
     'posts' => array(
      'order' => 'updatedAt DESC', 
      'limit' => 5 
     ) 
    ))->findAll(array(
     'condition' => 'userId = :userId AND ...', 
     'params' => array(
      'userId' => $userId 
     ), 

    )); 
+0

想到它。沒有幫助。 –

0

的關係()函數應該是這樣的:

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.