Reputation: 69
would like to update attached_blog_id field to set NULL. Thank you in advance.
foreach($this->Event->find('all', array('conditions' => array('Event.attached_blog_id' => $this->id()))) as $attached_blog)
$this->Event->query('UPDATE armo8427_events' . ' SET attached_blog_id = NULL' . ' WHERE id = ' . $attached_blog['Event']['id']);
Upvotes: 0
Views: 431
Reputation: 66227
The code in the question would be better written as:
$events = $this->Event->find(
'all',
array(
'conditions' => array(
'Event.attached_blog_id' => $this->id()
)
)
);
foreach($events as $event) {
$this->Event->id = $event['Event']['id'];
$this->Event->saveField('attached_blog_id', null);
}
With the code-logic in the question there is no need to use query at all
The logic in the question can be expressed as a single sql query, instead of 1+n:
UPDATE
events
SET
attached_blog_id = NULL
WHERE
attached_blog_id = $id;
I.e. if there were 100 linked blogs, using the foreach loop will issue 101 queries, wheras this is the same in one query irrespective of the number rof affected rows.
The most appropriate way to do that in CakePHP is to use updateAll:
$id = $this->id(); // From the question
$this->Event->updateAll(
array('Baker.attached_blog_id' => null), // the update
array('Baker.attached_blog_id' => $id) // conditions to match
);
the method query
should be reserved for sql calls which are not possible to achieve using the provided model methods.
Upvotes: 1