So, I have a table called posts and another called users.
CREATE TABLE `posts` (
`id` int(11) NOT NULL,
`users_id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`description` varchar(2000) NOT NULL,
`views` int(11) NOT NULL DEFAULT '0',
`status` int(1) NOT NULL,
`created` datetime DEFAULT CURRENT_TIMESTAMP,
`modified` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`created` datetime DEFAULT CURRENT_TIMESTAMP,
`modified` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
These are the respective models Posts and Users.
public function initialize(array $config)
{
parent::initialize($config);
$this->table('posts');
$this->displayField('title');
//$this->primaryKey(['id', 'users_id']);
$this->primaryKey(['id']);
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'users_id'
]);
}
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Posts', [
'foreignKey' => 'id'
]);
}
The problem is that when I enter a new post, the value of users_id comes as 0, even though in debug mode it appears as 1. This is the debug:
{
'users' => [
'users_id' => '1'
],
'title' => 'Teste title',
'description' => 'Test desc',
'status' => (int) 1,
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'users' => true,
'title' => true,
'description' => true,
'status' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Posts'
}
{ "users": { "users_id": "1" }, "title": "Teste title", "description": "Test desc", "status": 1 }
These are respectively the controller and the view:
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data, ['associated' => ['Users']]);
if ($this->Posts->save($post)) {
$this->Flash->success(__('The post has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The post could not be saved. Please, try again.'));
}
$users = $this->Posts->Users->find('list', ['limit' => 200]);
$this->set(compact('post', 'users'));
$this->set('_serialize', ['post']);
}
echo $this->Form->create($post);
echo $this->Form->input('users.users_id', array('default' => 1));
echo $this->Form->input('title');
echo $this->Form->input('description', ['rows' => '3']);
echo $this->Form->input('status', array('type'=>'select', 'options'=>array(1 => 'Enabled',2 => 'Disabled'), 'default'=>'1'));
echo $this->Form->button(__('Save Post'));
echo $this->Form->end();
I do not know what may be causing the error, the code seems the same as others I checked and that work.