Struggling to save in 2 tables with hasOne association


#1

Hello guys,
I’m struggling with the hasOne association. Here are my 2 tables :

Actually the ‘Etudiant’ (means student) has one User associated to it with the foreign key id present in both table which is the primary key of Users.

Here is the model Etudiant (student) : `class EtudiantTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('etudiant');
    $this->setDisplayField('ETUDIANT_ID');
    $this->setPrimaryKey('ETUDIANT_ID');
    $this->addBehavior('Timestamp');

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

    $this->belongsToMany('Tuteuriut', [
        'foreignKey' => 'ETUDIANT_ID',
        'targetForeignKey' => 'TUTEURIUT_ID',
        'joinTable' => 'Suivre'
    ]);
	$this->hasOne('Users', [
		'className' => 'Users',
		'foreignKey' => '_id',
		'bindingKey' => '_id',
		'joinType' => 'INNER'
	]);
}`

Here is the add function in the EtudiantController :
public function add()
{
$etudiant = $this->Etudiant->newEntity();
if ($this->request->is(‘post’)) {
$etudiant = $etutable->patchEntity($etudiant, $this->request->data(), [
‘associated’ => [‘Users’]
]);
if ($this->Etudiant->save($etudiant)){
$this->Flash->success((‘The etudiant has been saved.’));
return $this->redirect([‘action’ => ‘index’]);
}
$this->Flash->error(
(‘The etudiant could not be saved. Please, try again.’));
}
$this->set(compact(‘etudiant’));
}
I want to do this : when i insert an Etudiant it inserts a new user and both have the same id.
But currently when i insert an Etudiant i get an error saying “no default value…id is empty” but the id is supposed to be inserted automatically.


#2

I need help please i’m stucked