我在CakePHP中的相关表有问题。我无法获取表格中包含的相关表格数据。
我有两个实体。其中一个是“用户”,另一个是“主题”。每个用户都有一个主题。表“主题”具有用户表中的外键idUser。
我在UsersTable中添加了
$this->hasOne('Subjects');
然后我在SubjectsTable中添加了
$this->belongsTo('Users', [
'foreignKey' => 'idUser',
'joinType' => 'INNER'
]);
在视图(注册)中,我有这个:
<div class="form-group">
<?php echo $this->Form->control('Subject.name',['label' => 'Asignatura','placeholder' => 'Ingrese asignatura','class' => 'form-control']) ?>
</div>
在控制器中,我有这个:
$user = $this->Users->patchEntity($user, $this->request->getData(),['associated' => 'Subjects']);
调试$ user时,我得到以下结果:
\src\Controller\UsersController.php (line 113)
object(App\Model\Entity\User) {
'id' => '11111111',
'name' => 'Leo',
'firstlastname' => 'Messi',
'secondlastname' => 'Cuccittini',
'email' => 'leo.messi@gmail.com',
'password' => '$2y$10$E02nd/w89BDvgCyz36bQdeBbujOLrSdON1e6CD25aDYCP2VeLkNNm',
'role' => '2',
'[new]' => true,
'[accessible]' => [
'id' => true,
'name' => true,
'firstlastname' => true,
'secondlastname' => true,
'email' => true,
'password' => true,
'role' => true
],
'[dirty]' => [
'id' => true,
'name' => true,
'firstlastname' => true,
'secondlastname' => true,
'email' => true,
'password' => true,
'role' => true
],
'[original]' => [],
'[virtual]' => [],
'[hasErrors]' => false,
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Users'
}
因此,我没有从主题中获取控制器中的数据。
请帮助。
答案 0 :(得分:1)
模型
$this->hasOne('Subjects', [
'foreignKey' => 'userId'
]);
控制器:
$user = $this->User->get($id, ['contain' => ['Subjects']);
实体/User.php
protected $_accessible = [
'subjects' => true
// ...
];
表格
https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs
更改:将 Subject.name 更改为 user.subject.name
<?php echo $this->Form->control('user.subject.name',['label' => 'Asignatura','placeholder' => 'Ingrese asignatura','class' => 'form-control']) ?>