开发者

Updating multiple HABTM relationships in CakePHP

开发者 https://www.devze.com 2023-02-07 08:12 出处:网络
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 c

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?


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消