使用Belong将数据保存到很多cakehp 3.x.

时间:2017-04-18 17:31:55

标签: has-and-belongs-to-many belongs-to cakephp-3.x

我有两个表articlestags以及第三个关联表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表中,请不要知道有什么问题请帮帮我

由于

1 个答案:

答案 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;