0

在我的 cakephp (3.3) 项目中,如何在一次保存中保存多个表。我的关联如下,我也在这里给出我的代码。

表1:用户

在类用户表扩展表

$this->hasOne('ProfileDetails', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);

表 2:profile_details

在类 ProfileDetailsTable 中扩展 Table

$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);

保存多个表的数据格式应该是什么?在我的模板中,我添加了以下内容,现在我只使用了几个字段

$this->Form->input('User.username',['type' => 'text','class'=>'form-control']) ?>
$this->Form->input('User.password',['type' => 'password','class'=>'form-control']) ?>
$this->Form->input('User.email',['type' => 'text','class'=>'form-control']) ?>
$this->Form->input('ProfileDetail.first_name',['type' => 'text','class'=>'form-control']) ?>

在保存之前的控制器中,我已经调试过,结果如下

debug($this->request->data);
$user = $this->Users->patchEntity($user, $this->request->data);
debug($user); 
exit;
$this->Users->save($user)

调试结果

\src\Controller\UsersController.php (line 39)
[
'User' => [
'username' => 'Tester',
'password' => '43434324',
'email' => 'test@gmail.com',
'role' => 'admin'
],
'ProfileDetail' => [
'first_name' => 'Tester'
]
]
\src\Controller\UsersController.php (line 41)
object(App\Model\Entity\User) {

'User' => [
'username' => 'Tester',
'password' => '43434324',
'email' => 'test@gmail.com',
'role' => 'admin'
],
'ProfileDetail' => [
'first_name' => 'Tester'
],
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'User' => true,
'ProfileDetail' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [
'email' => [
'_required' => 'This field is required'
]
],
'[invalid]' => [],
'[repository]' => 'Users'

}

您能否建议我如何通过单次保存和验证将这些数据保存在多个表中?

4

2 回答 2

0

查看您的调试,有一个错误说电子邮件字段是必需的。也许那是你的问题..

于 2016-11-02T08:38:47.980 回答
0

如果还是不行,试试这个:

replace User by users
and ProjectDetail by project_details 

以你的形式。并从以下内容中删除 joinType:

$this->hasOne('ProfileDetails', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
于 2016-11-02T10:17:20.710 回答