保存两个模型的数据,信息来自“多个”<select>字段</select>

时间:2014-05-31 12:38:25

标签: php cakephp

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

http://i.stack.imgur.com/80b03.png(对不起,我无法在此处嵌入图像,我没有10个声誉)

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

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

我的Post.php和Category.php与CategoriesPost有HABTM关系,但是我尝试了很多配置,即使是&#34; hasMany through&#34;关系,但没有运气。作为参考,这是我在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')
        )));
    }

每次我推动&#34;创造&#34;按钮,Cake保存我的帖子,但不保存任何CategoriesPost或引发一些SQL错误,因为我保存了CategoriesPost而没有放入category_id或post_id。我该怎么做才能保存我的数据库中的所有信息?我应该更改$ this-&gt;数据数组的结构吗?作为参考,这是我在Post :: afterSave()中采用的$ this-&gt;数据数组:

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

请帮帮我:(

1 个答案:

答案 0 :(得分:0)

你真的不能这样做。 您在categories_posts中的post_id是在创建帖子记录后获得的($ this-&gt; Post-&gt; save(),之后$ this-&gt; Post-&gt; id将包含该ID)。 所以atm当你做save​​All你没有post id来创建categories_posts时,你需要先创建帖子,然后在一个大的saveAll中的categories_posts中创建所有条目。

这意味着您必须构建您将要执行的数据数组$ this-&gt; CategoriesPost-&gt; 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
    );
}
相关问题