I have tried to join two tables using hasOne association in my cakephp app
There are two tables users and admin. In both tables the id is primary key. i have linked the mobile field of admin to the add users table. So by hasOne association the user added in user table is supposed to be linked to admin and get added in admin table too. But i am unable to enter the user as an error is occuring
Here is the table structures
Here is the code of add page of the user template. It is the page to enter users
<?php
/**
* @var AppViewAppView $this
* @var AppModelEntityUser $user
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Users'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="users form content">
<?= $this->Form->create($user , ['type'=> 'file']) ?>
<fieldset>
<legend><?= __('Add User') ?></legend>
<?php
echo $this->Form->control('email');
echo $this->Form->control('password');
echo $this->Form->control('Re_enter_password');
echo $this->Form->control('admin.mobile');
echo $this->Form->control('image' , ['type'=> 'file']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
This is the user file in the Entity folder.I have added the admin = true in the accessible function so that admin will be accessible by user
protected $_accessible = [
'email' => true,
'password' => true,
'created' => true,
'modified' => true,
'articles' => true,
'admin' => true,
'status' => true,
'*' => true,
'id' => false
];
This is the add function in the UserController file. It is used to add new users
public function add()
{
$user = $this->Users->newEmptyEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if (!$user->getErrors) {
$image = $this->request->getUploadedFiles();
$name = $image['image']->getClientFilename();
$targetPath = WWW_ROOT.'img'.DS.$name;
if ($name) {
$image['image']->moveTo($targetPath);
}
$user->image = $name;
} else {
echo "Error uploading" ;
echo $user->getErrors;
}
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
}
This is the Users table file where i have defined the HasOne relation
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('email');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Articles', [
'foreignKey' => 'user_id',
]);
$this->hasOne('Admin');
}