2012-08-11 109 views
0

我正在製作一個電影網站項目。我需要限制5個評論每個電影頁面。如何限制cakephp中的遞歸

$this->Movie->find('first', array(
    'conditions' => array('Movie.url' => $req), // URL to fetch the required page 
    'recursive' => 1 
)); 

使用上面的代碼我得到1電影的細節和所有(目前近20)與該電影有關的評論。那麼我怎樣才能將評論限制在5?

+0

ofcourse,我會接受,如果它適合我​​。 我根本無法接受那些不適合我的人。 – 2012-08-12 02:18:34

回答

0

我想沒有人知道如何解決,我發現了一些我可以暫時解決的方法。 請有人告訴我最佳做法。

$movie = $this->Movie->find('first', array(
    'conditions' => array('Movie.url' => $req), 
'recursive' => 0 
)); 
$this->loadModel('MovieReview'); 
$movieReview = $this->MovieReview->find('all',array(
    'conditions' => array('MovieReview.movie_id' => $movie['Movie']['id']), 
    'limit' => 5, 
    'recursive' => -1 
)); 
$movie['MovieReview'] = $movieReview; 

如果有人需要回答這個問題,請回答最佳做法。

+0

沒有最佳實踐,因爲無法限制僅運行一個查詢的相關模型的結果。您必須運行第二個查詢或運行復雜/原始SQL查詢來完成此操作。 – rlcabral 2012-08-13 22:06:06

1

你可以試試這個:

$this->Movie->find('all', array(
    'conditions' => array('Movie.url' => $req), // URL to fetch the required page 
    'limit'=>5, 
    'recursive' => -1 
)); 
+0

不,這不起作用,因爲我在電影模型中沒有任何評論ID。請檢查我自己的答案。我修好了它。但我需要最佳實踐。 – 2012-08-12 10:44:26

0

對協會的嘗試,設定限制選項

 /** 
    * hasMany associations 
    * 
    * @var array 
    */ 
    public $hasMany = array(
     'MovieReview' => array(
      'className' => 'MovieReview', 
      'foreignKey' => 'movie_id', 
      'dependent' => false, 
      'conditions' => '', 
      'fields' => '', 
      'order' => '', 
      'limit' => '25', 
      'offset' => '', 
      'exclusive' => '', 
      'finderQuery' => '', 
      'counterQuery' => '' 
     ) 
    ); 
1
$this->Movie->find('all', array(
    'conditions' => array('Movie.url' => $req), // URL to fetch the required page 
    'contain' => array('MovieReview' => array('limit' => 5)) 
)); 

有了這個,你只會得到5 MovieReview每部電影返回

對不起,我的英語

+1

即使這可能是正確的答案,請不要猶豫,添加一些文本來解釋什麼代碼。 – AFract 2015-02-11 16:20:26