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

时间:2014-06-10 13:48:30

标签: php mysql cakephp

我在使用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 :(得分: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'));  
    }
}

答案 1 :(得分:0)

更改

return $userdetails;

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

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

虽然为什么要对它进行单独的查询,而不是仅仅使用'recursive' => 0来通过表连接获取关联的用户记录,您可以在视图中使用$chat['User']['firstname']

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

答案 2 :(得分:0)

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

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

仅此而已......