保存两个模型的数据,其中信息来自'multiple' <select> 字段



我正在建立一个博客,我遇到了一个问题。我想保存一个帖子,并将其链接到许多类别。这是我的数据库:

https://i.stack.imgur.com/80b03.png(对不起,我不能在这里嵌入图像,我没有10的声誉)

我想做的是保存一个新的帖子,然后保存许多CategoriesPost。这是我用于创建视图的代码:

echo $this->Form->select('CategoriesPost.category_id', $Categories, array(
    'multiple'  => true
));

我的Post.php和Category.php与categorespost有一个HABTM关系,但我尝试了很多配置,即使有"hasMany through"关系,但没有运气。作为参考,这是我在postscontroller。php

中使用的方法
public function admin_create() {
        if ($this->request->is('post')) {
            if ($this->Post->saveAll($this->request->data, array('deep' => true))) {
                $this->Session->setFlash('Post salvato', 'default', array(), 'good');
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Session->setFlash('Errore nel salvataggio', 'default', array(), 'bad');
        }
        $this->loadModel('Category');
        $this->set('Categories', $this->Category->find('list', array(
            'fields'    => array('id', 'category')
        )));
    }

每次我按下"创建"按钮,蛋糕保存我的帖子,但不保存任何categorespost或引发一些SQL错误,因为我正在保存categorespost而没有放入category_id或post_id。我应该怎么做,以保存所有的信息在我的数据库?我应该改变$this->data数组的结构吗?这是,作为参考,我的$ This ->数据数组采取Post::afterSave():

array(2) {
    ["CategoriesPost"]=>
    array(1) {
        ["category_id"]=>
        array(4) {
            [0]=> string(1) "3"
            [1]=> string(1) "4"
            [2]=> string(1) "5"
            [3]=> string(1) "6"
        }
    }
    ["Post"]=>
    array(4) {
        ["title"]=>string(1) "A"
        ["creation_date"]=> string(0) ""
        ["post"]=> string(1) "A"
        ["id"]=> string(3) "933"
    }
}

请帮帮我:

你不能这么做。在你的categories - _posts中的post_id是在你创建post记录之后获得的($this-> post ->save(),之后$this-> post ->id将包含那个id)。所以,当你做saveAll时,你没有创建categores_posts的帖子id,你需要首先创建帖子,然后在一个大的saveAll中创建categores_posts中的所有条目。

这意味着你将不得不建立数据数组,你将做$this-> categorespost ->saveAll($data)作为一组2对数组:

$data = array();
foreach($this->request->data['CategoriesPost']['category_id'] AS $category_id)
    $data[] = array(
        'post_id' => $this->Post->id,
        'category_id' => $category_id
    );
}

相关内容

最新更新