更新 CakePHP 中的多个 HABTM 关系

发布于 2024-10-14 19:58:11 字数 436 浏览 2 评论 0原文

在 Cake 说明书中,所有示例似乎都使用 save()/saveAll() 一次更新单个记录的 HABTM 关系。但是,我想使用一次调用创建多对多关联。例如,我有 3 个音乐会活动,并且有 2 个传单。我希望这两张传单与每个音乐会活动相关联。

我有 2 个表:eventsflyers 和一个联接表:events_flyers。所以我想我可以手动将记录添加到连接表中。但我想知道是否有某种方法可以做类似的事情:

$this->Event->updateAll(
  $flyers,
  array('festival_id' => $id)
)

或者 updateAll() 仅适用于常规字段?

In the Cake cookbook, all the examples seem to use save()/saveAll() to update HABTM relationships for a single record at a time. However, I'd like to create many to many associations using a single call. For example, I have 3 concert events, and I have 2 flyers. And I want those 2 flyers to be associated with each of the concert events.

I have 2 tables, events, flyers and a join table: events_flyers. So I suppose I could just add the records to the join table manually. But I was wondering if there was some way I could do something similar to:

$this->Event->updateAll(
  $flyers,
  array('festival_id' => $id)
)

Or does updateAll() only work on regular fields?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手长情犹 2024-10-21 19:58:11

此答案不使用 updateAll,但我知道您可以使用 save 创建 HABTM 关联,​​并在 $this->data 中专门键入数据>:

// load an Event
$this->data = $this->Event->read(null, $eventId);

// associate the Event with two Flyers
$this->data['Flyer']['Flyer'] = array($flyerId1, $flyerId2);

// save the Event (and HABTM associations)
$this->Event->save($this->data);

那么使用这个,您可以更进一步,将 saveAll 与多个事件记录一起使用吗?例如:

$this->data = $this->Event->find('all', array('conditions' => array('Event.id' => $eventIdList)));

foreach ($this->data as $event) {
    $event['Flyer']['Flyer'] = array($flyerId1, $flyerId2);
}

$this->Event->saveAll($this->data);

这对你有用吗?

This answer doesn't use updateAll, but I know that you can create HABTM associations using save and specially keyed data in $this->data:

// load an Event
$this->data = $this->Event->read(null, $eventId);

// associate the Event with two Flyers
$this->data['Flyer']['Flyer'] = array($flyerId1, $flyerId2);

// save the Event (and HABTM associations)
$this->Event->save($this->data);

So using this, could you take it a step further and use saveAll along with multiple Event records? For example:

$this->data = $this->Event->find('all', array('conditions' => array('Event.id' => $eventIdList)));

foreach ($this->data as $event) {
    $event['Flyer']['Flyer'] = array($flyerId1, $flyerId2);
}

$this->Event->saveAll($this->data);

Does that work for you?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文