我有一个提问和获得答案的网站。当提出问题时,我希望能够用多个主题标记新问题。使用多选,我已经向控制器发送了一组topic_ids。我一直在关注Cake的文档,但是我遇到了很多错误。
这是将关联实体与多对多关系链接起来的正确方法吗?如果需要,我可以提供更多信息或代码。
$question = $this->Questions->newEntity();
if ($this->request->is('post')) {
$topics = array_map(
function($id) {
$topic = $this->Questions->Topics->get($id);
$topic->_joinData = $this->Questions->TopicsQuestions->newEntity();
// user_id is metadata in the topics_questions table
$topic->_joinData->user_id = $this->Auth->User()->id;
return $topic;
},
// this is passed back as an array of topic_id
$this->request->data['topics'];
);
$this->Questions->Topics->link($question, $topics);
$question = $this->Questions->patchEntity($question, $this->request->data, ['associated' => ['Topics']]);
if ($this->Questions->save($question)) {
return $this->redirect(['action' => 'view', $question->id]);
} else {
$this->Flash->error(__('The question could not be saved. Please, try again.'));
}
}
答案 0 :(得分:0)
来自CakePHP API文档:
假设源实体和每个目标实体都是 已被持久化,如果它们被标记为新的或其状态是 未知然后会抛出异常。
因此,在保存问题后需要进行链接调用。