【问题标题】:Show the user's username in post view w/ related comment在带有相关评论的帖子视图中显示用户的用户名
【发布时间】:2014-02-08 13:26:17
【问题描述】:

我是 CakePHP 1.3 的新手...我想显示或显示 USER 的用户名而不是 USER 的 id,谁在 POST 视图中发布 COMMENTS...任何人都可以帮助我吗?

这是我做的模型关联:

  1. POSTS“有很多”评论
  2. 评论“属于”用户

发布->评论->用户

我已经阅读了 CakePHP 1.3 的 Containable Behavior,但我仍然不能很好地理解它...请帮助我在 post_controller 的 view 和 view.ctp 中放置什么代码,可以在 POST 中显示相关的相关表查看。

以及如何在 POST 视图中调用 USER 的数据。

我还是一头雾水。

提前致谢,Azure

【问题讨论】:

  • 请帮我解决这个问题! :{

标签: php cakephp cakephp-1.3 containable


【解决方案1】:

假设

你有如下三个表

(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);
}

app/View/Posts/文件夹中view.ctp文件的内容

<!-- 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',
        )
);
}
?>

【讨论】:

  • 非常感谢凯文!这些代码对我帮助很大。 :D
【解决方案2】:

我假设您将用户 ID 保存在 cmets 表中,并且用户名在发布评论的用户表中,然后使用以下解决方案

在控制器方法中:

$userdata=$this->User->find('all',array('fields'=>array('id','username'),'recursive'=>-1));
$userid=Set::extract('/User/id', $userdata);
$username=Set::extract('/User/username', $userdata);
$data=array_combine($username,$userid);
$this->set('name',$data);

在视图中:

$cid=$var['Comment']['user_id'];
$username=array_search($cid, $name);
echo $username;

【讨论】:

  • 感谢您花时间尝试解决我的问题 Arsh...我很感激。 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2011-06-30
  • 2018-10-14
  • 2019-05-23
  • 2012-07-20
  • 1970-01-01
相关资源
最近更新 更多