0
votes

In my cakephp (3.3) project, How to save multiple tables in a single save. My association is as follows, also I am giving my code here.

Table1 : users

In class UsersTable extends Table

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

Table2 : profile_details

In class ProfileDetailsTable extends Table

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

What should be the data format to save multiple tables? In my template I have added the following , for now I have used only few fields

$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']) ?>

In the controller before saving i have debuged which gives result as follows

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

Result of debug

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

'User' => [
'username' => 'Tester',
'password' => '43434324',
'email' => '[email protected]',
'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'

}

Could you please suggest me how to save this data in multiple tables with single save with validation?

2
put ProfileDetails instead ProfileDetail $this->Form->input('ProfileDetails.first_name' ...Jacek B Budzynski
@JacekBBudzynski Singular is the correct default, but it is also is ment to be underscored, ie profile_detail.ndm

2 Answers

0
votes

Looking at your debug, there is an error saying the email field is required. Maybe that is your problem..

0
votes

If still not working , try this:

replace User by users
and ProjectDetail by project_details 

In your form. And also remove joinType from following:

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