保存需要唯一的关联模型数据


Saving associated model data that needs to be unique

我构建了一个CakePHP应用程序,允许用户创建帖子并为其添加标签(主题)。数据库和关联的结构可以在这里看到:在 CakePHP 中为连接表设置包含

我已经设法通过连接表使用 Contains 成功提取数据。但是现在我正在尝试构建用户输入主题的部分,然后将其保存在主题表和Topic_post表中。

我有以下代码,我的添加新帖子方法:

if ($this->request->is('post'))
        {
            //$this->Post->create();
            if ($this->Post->save($this->request->data))
            {
                // Save extra data
                $this->Post->saveField('user_id', $this->Auth->user('id'));
                $this->Post->saveField('datetime', date('Y-m-d H:i:s'));
                $this->Post->saveField('modified', date('Y-m-d H:i:s'));
                $this->Post->saveField('status', 1);
                // Build slug
                $post_title = Sanitize::html($this->request->data['Post']['title'], array('remove'=>true, 'quotes' => ENT_NOQUOTES));
                $post_title = String::truncate($post_title, 50, array('exact'=>false,'html'=>false,'ending'=>''));
                $this->Post->saveField('slug', Inflector::slug($post_title));
                // Redirect the user to the newly created post (pass the slug for performance)
                $this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($this->Post->id),'slug'=>$this->Post->slug));
            }
            else
            {
                $this->Session->setFlash('Server broke!');
            }
        }

所以我现在需要做的是保存在此处输入的相关主题数据:

<?php echo $this->Form->create(); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.content', array('type'=>'textarea','label'=>false)); ?>
<?php echo $this->Form->input('Topic.title', array('type'=>'textarea','label'=>'Topics')); ?>
<button type="submit" class="orangeButton small">Create</button>
<?php echo $this->Form->end(); ?>

我看过 CakePHP 文档,似乎我需要的似乎是 saveAll ?但是我很困惑,因为我不是 100% 确定如何使用它,重要的是要注意用户可以将多个主题保存到数据库中,并且主题本身都是唯一的,因此例如,您无法创建已经存在的主题,而只会使用链接器的现有 id。

谁能帮忙?因为我觉得这相当复杂...

你可以做这样的事情:


$this->Post->saveAll($this->data, array('validate'=>'first'));

使用 array('validate'=>'first'); 确保我们的两个模型在保存之前都经过验证。你的意思是这样吗?

希望对你有帮助