【发布时间】:2017-08-19 21:45:19
【问题描述】:
我尝试将此example 应用于CakePHP3:表users 和messages (id, user_id, recipient_id, body) 与id 中的users 中的两个外键。
MessagesTable.php中的以下代码:
$this->belongsTo('Sender', [
'foreignKey' => 'user_id',
'className' => 'Users',
'propertyName' => 'Sender'
]);
$this->belongsTo('Recipient', [
'foreignKey' => 'recipient_id',
'className' => 'Users',
'propertyName' => 'Recipient'
]);
在MessagesController.php 在view 和index 方法中:
$message = $this->Messages->get($id, [
'contain' => ['Users'],
'contain' => ['Sender'],
'contain' => ['Recipient']
]);
在UsersTable.php:
$this->hasMany('MessagesSent', [
'foreignKey' => 'user_id',
'className' => 'Messages',
'propertyName' => 'MessagesSent'
]);
$this->hasMany('MessagesReceived', [
'foreignKey' => 'recipient_id',
'className' => 'Messages',
'propertyName' => 'MessagesReceived'
]);
在UsersController.php 和view 方法中:
$user = $this->Users->get($id, [
'contain' => ['MessagesSent'],
'contain' => ['MessagesReceived']
]);
不要在这个用户view.ctp中显示Related Messages:
<h4><?= __('Related Messages') ?></h4>
<?php if (!empty($user->messages)): ?>
<table cellpadding="0" cellspacing="0">
<tr>
<th scope="col"><?= __('Id') ?></th>
<th scope="col"><?= __('User Id') ?></th>
<th scope="col"><?= __('Recipient Id') ?></th>
<th scope="col"><?= __('Body') ?></th>
</tr>
<?php foreach ($user->messages as $messages): ?>
<tr>
<td><?= h($messages->id) ?></td>
<td><?= h($messages->user_id) ?></td>
<td><?= h($messages->recipient_id) ?></td>
<td><?= h($messages->body) ?></td>
</tr>
<?php endforeach; ?>
</table>
如果我只在UsersTable.php 和'contain' => ['Messages'] 中留下hasMany('Messages') 在UsersController.php 中,我确实在上面的view 中看到Related Messages,但显然只有那些与发件人相关的。
在这两种情况下,add 和 edit 消息都会导致错误:Table "App\Model\Table\MessagesTable" is not associated with "Users"。
有没有办法在 CakePHP3.x 中解决这个问题而无需添加连接表?我感觉我没有正确使用别名,但我不知道具体在哪里。
【问题讨论】:
标签: php mysql cakephp associations cakephp-3.0