D.Schaller
D.Schaller

Reputation: 651

CakePHP - belongsTo Data doesn't get saved to Join-Table

I have 3 Tables involved: UsersTable, RolesTable, UsersRolesTable

I want to assign a User a given Role when signing up, but it doesn't save the Data to the join-table(UsersRolesTable) and I don't know why.

Following associations are present:


UsersTable

$this->belongsTo('Roles', [
  'foreignKey' => 'user_id',
  'targetForeignKey' => 'role_id',
  'joinTable' => 'users_roles'
]);

RolesTable

$this->belongsToMany('Users', [
  'foreignKey' => 'role_id',
  'targetForeignKey' => 'user_id',
  'joinTable' => 'users_roles'
]);

UsersRolesTable

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

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

In my Users-controller I have the following function

public function register()
{
  $roles = TableRegistry::get('Roles');
  $role_data = $roles->findByName('User')->first();
  $user = $this->Users->newEntity();

  if ($this->request->is('post')) {
    $data = $this->request->getData();
    $user->profile = $this->Users->setDefaultProfile();
    $user->role = $role_data;
    $user = $this->Users->patchEntity($user, $data);
    if ($this->Users->save($user)) {
      $this->Flash->success(__('Ihr Account wurde erfolgreich angelegt. Sie können sich nun einloggen.'));

      return $this->redirect(['action' => 'login']);
    }
    $this->Flash->error(__('Ihr Account konnte nicht angelegt werden. Bitte versuchen Sie es später erneut.'));
  }
  $this->set(compact('user'));
}

I read in the book from cakephp but I can't get it working, nor wrap my head around it very well.

Can somebody see or explain the mistake I'm making here?


If you need further information please tell me.


Upvotes: 1

Views: 55

Answers (1)

D.Schaller
D.Schaller

Reputation: 651

The Problem was, that the whole skelleton was baked, and I didn't follow the naming conventions for this particular join-table.


From CakePHP - Conventions

Join tables, used in BelongsToMany relationships between models, should be named after the model tables they will join or the bake command won’t work, arranged in alphabetical order (articles_tags rather than tags_articles). If you need to add additional columns on the junction table you should create a separate entity/table class for that table.


Therefore my Relations were defined wrong. I had to delete the MVC for UsersRoles, rename my table from users_roles to roles_users and bake it again.

There is another way to handle that, and use the "wrongly" named table, but I decided to change the database according to the conventions since I followed them on every other part of my application.

BUT! I will reconfigure this scenario in near future and fiddle a way to resolve this problem with the custom named join-table.

Upvotes: 1

Related Questions