Reputation: 1901
I'm a bit confused with the following CakePHP outcome. I included code for two Model and one Controller (stripped out unnecessary stuff).
Problem: Everything saves correctly. The only issue is the user_id field for the store_users table does not save.
Anything obvious you can see that I'm doing wrong? I tried with both saveAssociated and saveAll.
Model/Store.php
<?php
App::uses('AppModel', 'Model');
class Store extends AppModel {
public $belongsTo = array(
'User'
);
public $hasMany = array(
'StoreUser'
);
}
Model/StoreUser.php
<?php
App::uses('AppModel', 'Model');
class StoreUser extends AppModel {
public $belongsTo = array(
'User',
'Store'
);
}
Controller/StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
public $uses = array('Store');
public function create() {
$this->Store->create();
$storeData = array(
'Store' => array(
'title' => 'New Store',
'user_id' => $this->Auth->user('id')
),
'StoreUser' => array(
'user_id' => $this->Auth->user('id')
)
);
if($this->Store->saveAll($storeData) !== false) {
// Success
} else {
// Error
}
}
}
Results in DB
stores table:
id: 1
title: New Store
user_id: 1
...
store_users table:
id: 1
store_id: 1
user_id: 0
...
Upvotes: 0
Views: 3753
Reputation: 1901
Found it! Because Store hasMany StoreUser and not Store hasOne StoreUser I must wrap the user_id
in the supplied data in an array.
Controller/StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
public $uses = array('Store');
public function create() {
$this->Store->create();
$storeData = array(
'Store' => array(
'title' => 'New Store',
'user_id' => $this->Auth->user('id')
),
'StoreUser' => array(
array(
'user_id' => $this->Auth->user('id')
)
)
);
if($this->Store->saveAll($storeData) !== false) {
// Success
} else {
// Error
}
}
}
Upvotes: 1