0

I have a Page model and a Category model. Basically, each page belongs to a category. The models are set up so Page belongsTo Category, and Category hasMany Page.

When adding new pages, I'm using this controller action:

public function admin_add() {
    if($this->request->is('post')) {
        $this->Page->create();
        if($this->Page->saveAssocated($this->request->data)) {
            $this->Session->setFlash('The page has been created.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to save the page.');
        }
    }
}

and this is the view for that action:

<h1>Add Page</h1>
<?php
    echo $this->Form->create('Page');
    echo $this->Form->input('Page.title', array('required' => 'required'));
    echo $this->Form->input('Page.body', array('type' => 'textarea', 'class' => 'redactor', 'required' => 'required'));
    echo $this->Form->input('Category.name');
    echo $this->Form->input('Page.in_header');
    echo $this->Form->end('Save Page');
?>

Now, when I save a page with "Services" as the category, it all gets saved correctly. The page gets saved and the category with name of "Services" gets inserted and they both get linked up properly.

However, when I add another page with the same category of "Services", instead of using the existing record in the categories table Cake makes a new one and links that one instead. I need it to use the existing record.

How can I fix my view/controller/database to make this work properly?

Thanks!

4

2 回答 2

1

你有几个解决方案来解决这个问题。

pollirata 提供的解决方案是一个非常好的解决方案。为用户提供现有类别的选择是了解哪些类别已存在的最简单方法。当您只需要一个简单的文本输入时,无论如何都会导致拼写错误或非常相似的类别名称。

如果要保留文本输入,则应在 beforeSave() 函数中检查 Page.php 模型中的现有类别:检索类别列表并将其与 $this->data['Category']['name '] 您尝试保存的数据。如果现有类别匹配,则在 $this->data['Category']['id] 中添加其 id,这样 Cake 就不会创建新记录。

于 2013-04-24T09:52:18.050 回答
0

创建记录时,没有地方可以指定现有类别的 id。因此,Cake 假定它是一条新记录,因为没有用于搜索的 ID。

您需要提供该类别的 id 以帮助 Cake 了解该记录已经存在

希望能帮助到你

于 2013-04-24T01:30:45.937 回答