[英]query and UPDATE in cakephp1.3
想要更新attach_blog_id字段以設置為NULL。 先感謝您。
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']);
問題中的代碼最好寫成:
$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);
}
使用問題中的代碼邏輯,根本無需使用查詢
問題中的邏輯可以表示為單個sql查詢,而不是1 + n:
UPDATE
events
SET
attached_blog_id = NULL
WHERE
attached_blog_id = $id;
也就是說,如果有100個鏈接的博客,則使用foreach循環將發出101個查詢,而在一個查詢中這是相同的,而與受影響的行數無關。
在CakePHP中最合適的方法是使用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
);
方法query
應保留給使用提供的模型方法無法實現的sql調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.