Reputation: 51
I am having trouble saving associated data in Cake 3.0. I have a Users Model, and a user can be many different musicians. I have a join table users_musicians.
class UsersTable extends Table {
public function initialize(array $config) {
$this->addBehavior('Timestamp');
$this->belongsToMany('Musicians', [
'joinTable' => 'users_musicians',
]);
$this->belongsTo('Counties', [
'foreignKey' => 'county_id',
'joinType' => 'INNER',
]);
}
I am posting over a new user, and trying to save a single musician type in the users_musicians table, using the musician_id posted over and using the user_id of the new user saved.
public function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$newData = [
'users_musicians' => [
['musician_id' => 10],
]
];
$this->Users->patchEntity($user, $newData);
echo '<br><br><pre>' . print_r($user, true) . '</pre>';
//die();
if ($this->Users->save($user)) {
$this->Flash->success(__('Your details have been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your details.'));
}
$this->set('user', $user);
}
Table structue of "users_musicians" is: id - int, AI, PK, user_id - int, musician_id - int, created - datetime, updated - datetime
Any suggestions?
Upvotes: 2
Views: 805
Reputation: 1889
In CakePHP for belongsToMany association the table name should be in alphabetical order so, change the "users_musicians" table name to "musicians_users" and try it.
Upvotes: 2