【发布时间】:2013-01-07 00:26:09
【问题描述】:
我有一个Post 模型和Tag 模型,它们都通过HABTM 关系正确设置。我的数据库中还有一个名为 posts_tags 的表,根据命名约定正确命名。
但是,我终其一生都无法弄清楚如何将标签与帖子一起保存。在我的“添加帖子”页面上,我有这个:
<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.name'); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Publish'); ?>
在提交时调用此操作:
public function add() {
if($this->request->is('post')) {
if($this->Post->saveAll($this->request->data)) {
$this->Session->setFlash('Post published!');
$this->redirect('/');
} else {
$this->Session->setFlash('Post unable to be saved!');
}
}
$this->set('pageTitle', 'Compose new blog post');
}
帖子保存但不保存标签或帖子与标签之间的关系,Cake没有给我错误或警告。我需要做什么才能让 Cake 将标签与帖子一起保存并建立所需的关系?
编辑:这是$this->request->data 中的内容的转储,使用saveAll() 将其保存到数据库中:
array(
'Post' => array(
'title' => 'Blog post',
'body' => 'Testing this post',
'slug' => 'Blog-post'
),
'Tag' => array(
'name' => 'test-tag'
)
)
【问题讨论】:
-
标签是否保存在您的
tags表中? -
不,
posts_tags中的标签和关系都不是。 -
我已编辑问题,为您提供
$this->request->data的输出。
标签: php cakephp has-and-belongs-to-many