【问题标题】:Cakephp 3.x Saving multiple tablesCakephp 3.x 保存多个表
【发布时间】:2016-11-02 06:34:22
【问题描述】:

在我的 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'

}

您能否建议我如何将这些数据保存在多个表中,并进行一次保存并进行验证?

【问题讨论】:

  • ProfileDetails 改为 ProfileDetail $this->Form->input('ProfileDetails.first_name' ...
  • @JacekBBudzynski Singular 是正确的默认值,但也需要强调,即profile_detail

标签: associations cakephp-3.0 savemany


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    replace User by users
    and ProjectDetail by project_details 
    

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

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

    【讨论】:

    • 而不是 User.username , User.password 和 User.email 尝试只使用用户名、密码和电子邮件...并保留 project_details.first_name 为 ProjectDetail.first_name ..
    • @ManoharKhadka hasOne 关联默认使用单数名称,即profile_detail。此外,连接类型与保存无关,而仅与检索数据有关。
    • 以下数据仍然没有运气 \src\Controller\UsersController.php (line 51) [ 'username' => 'testuser', 'password' => '123456', 'email' = > 'testuser@gmail.com', 'role' => '作者', 'profile_details' => ['first_name' => 'test', 'last_name' => 'fname', 'phone' => '444444' ] ]
    猜你喜欢
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多