我有两个表articles
和tags
以及第三个关联表articles_tags
现在我想在创建新文章时保存articles_tags中的数据,用户从下拉我的控制器代码中选择多个标签在下面
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->data, [
'associated' => ['Tags']
]);
if ($this->Articles->save($article)) {
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$tags = $this->Articles->Tags->find('list',[
'keyField' => 'id',
'valueField' => 'name'
]);
$this->set(compact('article','tags'));
$this->set('_serialize', ['article','tags']);
}
我的观看代码在
下面<?php
$this->Form->create($article);
echo $this->Form->input('title');
echo $this->Form->input('status');
echo $this->Form->select('tags.tag_id',
$tags,
['empty' => '(choose one)', 'multiple' => true,]
);
echo $this->Form->button(__('Submit'));
echo $this->Form->end();
?>
我的文章和标签型号代码在
之下public function initialize(array $config)
{
parent::initialize($config);
$this->table('articles');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Tags', [
'foreignKey' => 'article_id',
'targetForeignKey' => 'tag_id',
'joinTable' => 'articles_tags'
]);
}
public function initialize(array $config)
{
parent::initialize($config);
$this->table('tags');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Articles', [
'foreignKey' => 'tag_id',
'targetForeignKey' => 'article_id',
'joinTable' => 'articles_tags'
]);
}
但是当我保存数据而不是数据只保存在文章表中时,只有相关的标签ID和文章ID不能保存在article_tags
表中,请不要知道有什么问题请帮帮我
由于
答案 0 :(得分:0)
更正您的观看代码
<?php
$this->Form->create($article);
echo $this->Form->input('title');
echo $this->Form->input('status');
echo $this->Form->select('tags._ids',
$tags,
['empty' => '(choose one)', 'multiple' => true,]
);
echo $this->Form->button(__('Submit'));
echo $this->Form->end();
&GT;