2011-02-23 28 views
1
他們的最新評論的帖子

說我有一個模型Post及相關作爲模型Comment如下:獲取與CakePHP中

Post hasMany Comment 
Comment belongsTo Post 

如何使用find('all')檢索每Post與其相關的最新Comment

我曾嘗試在Post定義爲hasOne關係:

var $hasOne = array('LatestComment' => array('className' => 'Comment', 'order' => 'LatestComment.created DESC')); 

但是當我做了Post->find('all')它的每一個Post多次返回,每各Comment一次,LatestComment設置爲不同的Comments

+0

可能與我的問題有關:http://stackoverflow.com/questions/8707048/last-x-blog-entries-but-only-once-per-user/11933591#11933591 – mark 2012-08-25 21:08:45

回答

2

您可以將'limit'=> 1添加到您的參數數組中以僅返回一個評論。

或者,您可以使用可包含行爲簡單地限制執行查找時返回的註釋數量,而不是定義其他關係。

$this->Post->find('all',array(
        'contain' => array(
          'Comment' => array(
           'order' => 'Comment.created DESC', 
           'limit' => 1 
         ) 
        ) 
       ); 

,如果你想沒有確定的關係,以過濾任何相關集這是有用的 - 由作者或日期範圍內,例如。

確保您將可包含行爲添加到您引用的任何模型。

+0

我其次。始終使用Containable! – OldWest 2011-02-24 03:45:15

+0

hasOne關係似乎不支持選項'限制'(請參閱http://book.cakephp.org/#!/view/1039/Associations-Linking-Models-Together)您的第二個建議可行,但我會喜歡通過hasOne關係查看方法,因此latestComment可以用作任何其他相關模型(自動添加到查詢中)。 – zephyr 2011-02-24 19:09:59

+0

您可以使用hasMany並將其限制爲1個結果。這似乎違反直覺,但它應該工作。 – NathanGaskin 2011-02-25 10:13:48

0

刪除要使用的重複項:GROUP BY在查找所有查詢中。我相信Cake也有一個'group'=>選項。

+0

這確實只給我每個帖子的一個,但沒有正確的(最新的)評論。 – zephyr 2011-02-24 19:18:05

+0

正確的你需要擴展它來做你的查詢的其他部分。按DESC排序,然後從數組結果中獲取第一個元素。 – OldWest 2011-02-25 01:24:35