I have tables
users, projects, project_roles and project_users.
I want to create project, project_role (two default) and then add user to one of that roles all at once.
Problem is adding user. Table project_users has project_role_id field which doesn’t get filled.
Here is what i tried.
$project = $this->Projects->newEntity();
$project_role_default = $this->Projects->ProjectRoles->newEntity();
$project_role_manager = $this->Projects->ProjectRoles->newEntity();
$project_role_user = $this->Projects->ProjectUsers->newEntity();
if ($this->request->is('post')) {
$project = $this->Projects->patchEntity($project, $this->request->getData());
$project_role_default->title = 'Collaborator';
$project_role_manager->title = 'Manager';
$project_role_manager->is_manager = 1;
**$project_user->project_role_id = ???? // doesn't get automatically filled as project_id, i tried $project_role_manager->id (id is acessible) but that doesn't work either**
$project->project_roles = [$project_role_default, $project_role_manager];
$project->project_users = [$project_user];
if ($this->Projects->save($project)) {
$this->Flash->success(__('Project successfully created.'));
return $this->redirect(['project_roles' => 'index']);
}
}
$this->set(compact('project', 'project_roles', 'project_users'));
And i get this error without bold line
General error: 1364 Field ‘project_role_id’ doesn’t have a default value
Here is what I did to make it work. But I believe there is a correct way to do it?
$project = $this->Projects->newEntity();
$project_role_default = $this->Projects->ProjectRoles->newEntity();
$project_role_manager = $this->Projects->ProjectRoles->newEntity();
if ($this->request->is('post')) {
$project = $this->Projects->patchEntity($project, $this->request->getData());
$project_role_default->title = 'Collaborator';
$project_role_manager->title = 'Manager';
$project_role_manager->is_manager = 1;
$project->project_roles = [$project_role_default, $project_role_manager];
if ($result = $this->Projects->save($project)) {
$project_user = $this->Projects->ProjectUsers->newEntity();
$project_user->user_id = $this->Auth->user('id');
$project_user->project_id = $result->id;
$query = $this->Projects->ProjectRoles->find('all', [
'conditions' => ['project_id =' => $result->id, 'title =' => 'Manager']
]);
$role = $row = $query->first();
$project_user->project_role_id = $role->id;
if($this->Projects->ProjectUsers->save($project_user)){
$this->Flash->success(__('Project successfully created.'));
return $this->redirect(['project_roles' => 'index']);
}
}
}
$this->set(compact('project', 'project_roles'));