我想不出如何做到這一點,也許是正確的方式,所以我選擇使用元素來實現這一點。基本上,在foreach $comments
的每次迭代中,我打電話給childrenComments
元素以檢查是否有兒童對當前$comment['Comment']['id']
的評論。如果有評論,我會使用每條評論在其父評論下面顯示每條評論。請參見下面的一些代碼....
守則articles_controller.php
function childrenComments($id = null){
$comments = $this->Article->Comment->find(
'all',
array(
'fields' => array(
'Comment.id',
'Comment.comment',
'User.username',
'User.image'
),
'conditions' => array(
'Comment.parent_id =' => $id,
'Comment.approved =' => 1
)
)
);
return $comments;
}
元childrenComments.ctp
<div style="width:100%;">
<div>
<?php
$childrenComments = $this->requestAction('/articles/childrenComments/'.$id);
foreach ($childrenComments as $childrenComment){
?>
<table cellpadding=0 cellspacing=0>
<tr>
<td>
<img style="width:30px;margin-right:5px" src="<?php echo $childrenComment['User']['image'];?>">
</td>
<td width=100% style="padding-left:10px;">
<?php
echo $childrenComment['Comment']['comment'];
?>
</td>
</tr>
</table>
<?php
}
?>
</div>
代碼在我/articles/view.ctp
<?php
foreach($comments as $comment){
...
//Code are placed here to display each parent comment
...
//This will iterate and display all children comments
echo $this->element('childrenComments',array('id' => $comment['Comment']['id']));
}
?>
其結果是:
我有lft字段以及rght字段。但是,我的問題將是如何實現這一點。我已經做了一些更多的研究並發現了CakePHP樹行爲,但是,我還沒有圍繞如何實現它的方法來包裝我的大腦。我已經使用'foreach $ comments作爲$ comment'來顯示父註釋。我如何從那裏分支並顯示每個家長的孩子評論?我會稍後嘗試發佈一些代碼。另外,我在哪裏添加'ActsAs =數組('樹')?在「文章」或「評論」模型中?例如,從'Article'我使用'$ this-> Article-> Comment-> id'。 –