【发布时间】:2014-06-10 13:48:29
【问题描述】:
我无法在使用 cakePHP 的聊天视图中链接来自表用户的名字等数据。下面是我的代码,无论我做什么,脚本都不会从聊天数据库表中选择 user_id 来显示名字。我必须监督一些事情,但我正在考虑的循环让我有些头疼。有人可以让我摆脱这个循环吗?
用户.php
<?php
class User extends AppModel {
public $hasMany = array(
'Ondutylog',
'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
)
【问题讨论】: