【问题标题】:Saving associated model data that needs to be unique保存需要唯一的关联模型数据
【发布时间】:2012-04-09 09:45:06
【问题描述】:

我已经构建了一个 CakePHP 应用程序,它允许用户创建帖子并向它们添加标签(主题)。数据库和关联的结构可以在这里看到:Setting up contains for a join table in CakePHP

我已经成功地通过连接表使用 Contain 提取数据。但现在我正在尝试构建用户输入主题的部分,然后将其同时保存在主题表和 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。

有人可以帮忙吗?因为我觉得这相当复杂......

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    你可以这样做:

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

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

    希望对你有帮助

    【讨论】:

    • 我不完全确定。我的意思是 CakePHP 只是自动处理所有链接并知道将哪个表放在哪里? IE。更新 Post 表、Topic 表和 Topic_Posts 连接表?
    • cakePHP 会处理它,如果你有维护关系,比如 Topic belongsTo Post 等
    • 逗号分隔的标签呢? cake 如何知道为每个创建一行并为每个创建一个链接?
    • 例如,如果用户在 Topic.title 框中键入 tag1, tag2, tag3 我希望它在 Topics 表中创建 3 个标签,并在 Topic_Posts 表中创建将每个标签链接到帖子的 3 个链接.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多