首页 文章

CakePHP无法链接模型中2个表的数据

提问于
浏览
0

我在使用cakePHP查看聊天视图中的表中的用户链接数据时遇到问题 . 下面是我的代码,无论我做什么,脚本都不会从聊天数据库表中选择user_id来显示第一个名称 . 我必须要监督某些事情,但我正在思考的循环让我感到头痛 . 有人可以让我离开这个循环吗?

user.php的

<?php
class User extends AppModel {
    public $hasMany = array(
        'Ondutylog',
        'Chat'
        );
}
?>

Chat.php

<?php
class Chat extends AppModel {
    public $belongsTo = array(
        'User'
        );
}
?>

ChatsController.php

<?php
class ChatsController extends AppController {
    var $uses = array('User', 'Chat');
    public function view() {
        $chats = $this->Chat->find('all', array(
            'order' => array('id' => 'ASC'),
            'recursive' => -1
            ));
        $this->set('chats', $chats);
        $id = $chats['Chat']['user_id'];
        $userdetails = $this->Chat->User->find('first', array(
            'conditions' => array(
                'id' => $id
                ),
            recursive' => -1
            ));
        return $userdetails;
    }
}
?>

view.ctp

<?php 
foreach($chats as $chat) :
    echo "<tr>";
    echo "<td>".$userdetails['User']['firstname']."</td>";
    echo "<td>".$chat['Chat']['user_id']."</td>";
    echo "<td>".$chat['Chat']['text']."</td>";
    echo "<td>".$chat['Chat']['created']."</td>";
    echo "</tr>";
endforeach 
?>

我在$ chats中返回的数组

[Chat] => Array
    (
        [id] => 1
        [user_id] => 11
        [text] => hello
        [created] => 2014-05-21 19:56:16
        [modified] => 2014-05-21 19:56:16
    )

3 回答

  • 0

    更改

    return $userdetails;
    

    $this->set(compact('userDetails'));
    

    您应该设置视图var不返回信息 .

    虽然你为什么要为它做一个单独的查询,而不是只使用 'recursive' => 0 ,它将通过表连接获得关联的用户记录,你可以在视图中使用 $chat['User']['firstname'] .

    也摆脱 var $uses = array('User', 'Chat'); . 这不是必需的 . $this->Chat 已经可用,用户模型通过关联访问 $this->Chat->User ,就像您已经完成的那样 .

  • 0

    您需要在控制器中为模型充电

    class ChatsController extends AppController {
    
        public function view() {
            $this->loadModel('User');
            $this->loadModel('Chat');
            $chats = $this->Chat->find('all', array(
                'order' => array('id' => 'ASC'),
                'recursive' => -1
                ));
            $this->set('chats', $chats);
            $id = $chats['Chat']['user_id'];
            $userdetails = $this->Chat->User->find('first', array(
                'conditions' => array(
                    'id' => $id
                    ),
                recursive => -1
                ));
           $this->set(compact('userDetails'));  
        }
    }
    
  • 0

    我找到了解决方案,它比我想象的更接近 . 因为模型用户和聊天已经加入,我只需要在Controller中使用几行 . 所以我修改它像这样:

    public function view() {
        $chats = $this->Chat->find('all');
        $this->set('chats', $chats);
    }
    

    仅此而已......

相关问题