【发布时间】:2011-07-12 12:48:31
【问题描述】:
我想知道你们是否可以帮助解决一个复杂的问题。
我有三张表。
用户、职位和评论。
职位分配给用户,但任何用户都可以对职位发表评论。
目前,通过传统方式烘焙后,View Job 视图在底部显示相关 cmets。但是,评论表显示一个数字user_id,而我希望它显示与所述user_id 匹配的“用户名”。
在View Job 视图中,我有这个数组,以及它们各自的键:
$job;
$job['Users'];
$job['Comments'];
$job['Job'];
这是我对 $job 数组的调试输出。
Array
(
[Job] => Array
(
[id] => 1
[user_id] => 1
[title] => New Job
[body] => adsljbfalwsjbflkjb
[deadline] => 2011-07-15
[completed] => 0
)
[User] => Array
(
[id] => 1
[username] => dan
[password] => 2fd27a6319ef3faf9ed55b59830d786b5ed890be
)
[Comment] => Array
(
[0] => Array
(
[id] => 3
[job_id] => 1
[user_id] => 2
[hours] => 6
[body] => Comment from Phil
[date] => 2011-07-12
)
[1] => Array
(
[id] => 2
[job_id] => 1
[user_id] => 1
[hours] => 2
[body] => This is a Comment from the 9th
[date] => 2011-07-09
)
)
)
我能不能用这些来显示用户名而不是 user_id?我要修改模型吗?控制器?
我对 CakePHP 比较陌生,虽然我已经掌握了基础知识,但我在处理像这样的更复杂的查询时遇到了困难。
这是我要更改的视图文件:
<div class="related">
<h3><?php __('Comments'); ?></h3>
<?php if (!empty($job['Comment'])): ?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<th><?php __('User'); ?></th>
<th><?php __('Date'); ?></th>
<th><?php __('Hours'); ?></th>
<th><?php __('Body'); ?></th>
<th class="actions"><?php __('Actions'); ?></th>
</tr>
<?php
$i = 0;
foreach ($job['Comment'] as $comment):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class; ?>>
<td><?php echo $comment['user_id']; ?></td> // NEEDS TO BE USERNAME NOT USER ID
<td><?php echo $comment['date']; ?></td>
<td><?php echo $comment['hours']; ?></td>
<td><?php echo $comment['body']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View', true), array('controller' => 'comments', 'action' => 'view', $comment['id'])); ?>
<?php echo $this->Html->link(__('Edit', true), array('controller' => 'comments', 'action' => 'edit', $comment['id'])); ?>
<?php echo $this->Html->link(__('Delete', true), array('controller' => 'comments', 'action' => 'delete', $comment['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $comment['id'])); ?>
</td>
</tr>
<?php endforeach; ?>+
</table>
<?php endif; ?>
</div>
感谢您的帮助!
【问题讨论】:
-
在您看来,
debug($job)并发布您所拥有的。我敢打赌它已经在里面了。 -
@Jason McCreary 我已经用输出更新了问题。
-
需要查看一些控制器/模型代码,但是这是可能的。你在修改
$this->Model->recursive吗?这可以影响关联的深度,而无需任何额外的工作。 -
您必须在模型上设置 $displayField。请参阅下面的答案...
-
$this->Model->recursive不适合您,因为您正在寻找模特孩子的另一个父母。