個假設
您有三個表如下
(1) Posts
* id
* title
(2) Comments
* id
* post_id
* user_id
(3) Users
* id
* name
查看功能在PostsController.php文件
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->Post->recursive=2;
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
內容view.ctp文件在app /查看/帖子/文件夾
<!-- File: /app/View/Posts/view.ctp -->
<h1><?php echo 'Post ID : '.h($post['Post']['id']); ?></h1>
<h1><?php echo 'Post Title : '.h($post['Post']['title']); ?></h1>
<?php
echo 'Comments By Users : ';
if(!empty($post['Comment'])){
foreach ($post['Comment'] as $key=>$value){?>
<p>User Name : <?php echo $value['User']['name'];?></p>
<?php }
}
else {
echo '<br/>';
echo 'No Comments Yet';
} ?>
模型文件:user.php的
<?php
class User extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
);
}
?>
模型文件:Comment.php
<?php
class Comment extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
?>
模型文件:post.php中
<?php
class Post extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
)
);
}
?>
幫我解決這個請! :{ – Azure