Speichern Sie Assoziationen mit Cakephp 3

Ich habe ein Problem mit CakePHP 3 und speichere neue Entität und ihre Assoziationen mit einer Operation.

einer Meinung nach mache ich es wie in der Dokumentation empfohle

Hier mein 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']
        ]);
    }
}  

Das ist meine Modelle:

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'
        ]);    
}  

Und das ist meine Datenbank:

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;

Mein Formular sieht so aus:

<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]"> 

Ich möchte ein Formular erstellen, das alle Verknüpfungen enthält, und es mit einer Anforderung speichern.

Antworten auf die Frage(1)

Ihre Antwort auf die Frage