I have a problem with CakePHP 3 and saving new entity and its associations with one operation.
In my opinion I do it like recommended in the documentation.
Here my controller:
$articles = TableRegistry::get('Articles');
$article = $articles->newEntity($this->request->data);
if ($this->request->is('post')) {
$valid = $articles->validate($article, [
'associated' => ['Topics']
]);
if ( $valid ) {
$articles->save($article, [
'validate' => false,
'associated' => ['Topics']
]);
}
}
Thats my models:
class ArticlesTable extends Table {
public function initialize(array $config) {
$this->primaryKey('article_id');
$this->belongsTo ( 'Topics', [
'targetForeignKey' => 'topic_id'
]);
}
}
class TopicsTable extends Table {
public function initialize(array $config) {
$this->primaryKey('topic_id');
$this->hasMany ( 'Articles', [
'targetForeignKey' => 'article_id'
]);
}
And this is my database:
CREATE TABLE `articles` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`topic_id` int(11) DEFAULT NULL,
PRIMARY KEY (`article_id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;
CREATE TABLE `topics` (
`topic_id` int(11) NOT NULL AUTO_INCREMENT,
`topic_title` varchar(45) DEFAULT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
MY form looks like that:
<input type="text" id="articles-heading" maxlength="45" required="required" name="Articles[heading]">
<input type="text" id="articles-topics-topic-title" list="topics" name="Articles[Topics][topic_title]">
I want to create a form which contains all the associations and save it with one request.