我了解MVC一点,但我是新的CakePHP。我认为我的问题很简单,但是无论我尝试了多少方法,我都无法检索到我正在寻找的数据。
让我们从2个模型开始:用户和活动。用户--(有许多活动)-id-name
活动(属于用户)-id-用户id(与用户id相关)-创建人(与用户id相关)
现在,在我的活动视图中,user_id和created_by都显示了用户名...这就是我想要的,但是在我的用户view.cpt烘焙给了我一个用户信息下的部分,列出了与我是用户相关的活动查看,但在此列表中,仅显示用户的ID。
以下是我的用户/视图中的烘焙代码。cpt
<?php
$i = 0;
foreach ($user['Activity'] as $activity): ?>
<tr>
<td><?php echo $activity['id']; ?></td>
<td><?php echo $activity['title']; ?></td>
<td><?php echo $activity['description']; ?></td>
<td><?php echo $activity['user_id']; ?></td>
<td><?php echo $activity['created_by']; ?></td> //I Want the User's NAME not iD
<td><?php echo $activity['due_date']; ?></td> //I Want the User's NAME not iD
<td><?php echo $activity['created']; ?></td>
<td><?php echo $activity['modified']; ?></td>
<td><?php echo $activity['cfc_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'activities', 'action' => 'view', $activity['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'activities', 'action' => 'edit', $activity['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'activities', 'action' => 'delete', $activity['id']), null, __('Are you sure you want to delete # %s?', $activity['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
我知道我将不得不到处这样做(因为我所有的模型都是基于一个用户的),检索这些数据的正确方法是什么。我曾尝试向模型和用户/活动控制器添加方法,但似乎无法正确访问这些方法。
把这段代码放在你的Activity.php
模型类中:
public $belongsTo = array('User' => array('className' => 'User',
'foreignKey' => 'user_id'),
'Creator' => array('className' => 'User',
'foreignKey' => 'created_by'));
在控制器的类方法中:
$this->Activity->find('all', array('conditions' => array('Activity.user_id' => $user_id)));
在您的视图文件中:
<?php
$i = 0;
foreach ($user['Activity'] as $activity): ?>
<tr>
<td><?php echo $activity['id']; ?></td>
<td><?php echo $activity['title']; ?></td>
<td><?php echo $activity['description']; ?></td>
<td><?php echo $activity['User']['username']; ?></td> //username is the name of user
<td><?php echo $activity['Creator']['username']; ?></td> //username is the name of user
<td><?php echo $activity['due_date']; ?></td>
<td><?php echo $activity['created']; ?></td>
<td><?php echo $activity['modified']; ?></td>
<td><?php echo $activity['cfc_id']; ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('controller' => 'activities', 'action' => 'view', $activity['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('controller' => 'activities', 'action' => 'edit', $activity['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('controller' => 'activities', 'action' => 'delete', $activity['id']), null, __('Are you sure you want to delete # %s?', $activity['id'])); ?>
</td>
</tr>
<?php endforeach; ?>