【问题标题】:Save relationships between many existing records and one new record保存许多现有记录和一条新记录之间的关系
【发布时间】:2014-01-07 12:40:13
【问题描述】:

使用 CakePHP,我有事件和人物。我想在保存新事件时将许多现有人员分配给我正在创建的事件。我正在使用复选框选择人员。

我的数据如下:

data[Event][name]:Test 4
data[Event][event_type_id]:1
data[EventPerson][person_id]:
data[EventPerson][person_id][]:65
data[EventPerson][person_id][]:72
data[EventPerson][person_id][]:67

我有 EventPerson 模型,设置了彼此之间的 HABTM 关系,还有一个 events_people 表和模型,并且这些设置正确。

我试过$this->Event->saveAssociated$this->Event->saveAll。每个人都会用正确的信息保存事件记录,也不保存与人的关系。

保存事件时,人们将始终已经存在。我觉得我错过了一些明显的东西,但我已经绞尽脑汁好几个小时了,结果没有任何变化。

试过

控制器

$this->Event->create();
    if ($this->Event->save($this->request->data)) {
        $this->Session->setFlash(__('The event has been saved'));
        return $this->redirect...
    }
$people= $this->FestivalPerson->find('all', 
    array(
        "Person.name",
        "conditions" => array(
            "festival_id" => $this->request->query["festival_id"]
        ), 
        "order" => "Person.name ASC"
    )
);
$this->set("eventPeople", Set::combine($people, '{n}.Person.id', '{n}.Person.name'));

查看:

echo $this->Form->input('EventPerson', array('multiple' => 'checkbox'));

数据:

data[Event][EventPerson]:
data[Event][EventPerson][]:50
data[Event][EventPerson][]:65
data[Event][EventPerson][]:71

看起来它与每个示例的结构匹配并且应该正确保存,但我的 events_people 表仍然是空的。 PHP/MySQL 也没有任何错误。

【问题讨论】:

  • @AD7six 添加了更多信息。这是控制器/视图的相关部分,它根据传递的节日 id 获取人员列表(我在该节日创建事件时列出与节日相关的人。只有与节日相关的人才会出现在事件。)
  • 这不是尝试保存 HABTM 关系的正确表单/数据结构 - 因此它不起作用。
  • @AD7six 我目前无法尝试 J.D. 的答案,但我相信你们对数据结构错误的看法都是正确的。有没有合适的方法来创建我缺少的表单元素?我宁愿不手动操作数据。
  • 参见the docs (near the end of that section) 或例如this answer,或使用 bake 生成工作视图并进行编辑。基本上你想要echo $this->Form->input('EventPerson') - 随时将此评论作为答案并在你找到解决方案后接受它。
  • irc频道是one of the places to get helpirc简直就是一个聊天室。例如this is the log for CakePHP's main chat room。只需写下您所做的和更改的内容作为答案并接受它 - 这已经足够了 =)。

标签: cakephp save has-and-belongs-to-many


【解决方案1】:

这样形成你的数据

data[Event][name]:Test 4
data[Event][event_type_id]:1
data[EventPerson][0][person_id]:
data[EventPerson][1][person_id][]:65
data[EventPerson][2][person_id][]:72
data[EventPerson][2][person_id][]:67

或关注本文:http://patisserie.keensoftware.com/en/pages/how-to-save-habtm-data-in-cakephp

它解释了如何在 cakePhp 中为数据数组编写自定义代码,我相信那里有类似的例子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多