限制结社我有事件属于关联地点关联。 当用户试图删除场地时,我不希望在一个或多个事件与其关联时发生。 什么是最自动的方式来做到这一点?实施ondelete CakePHP中
1
A
回答
1
如果安装上的关系counterCache和使用deleteAll而不是删除您可以通过条件基于连接到会场的事件数量删除查询。
<?php
/**
* Event Model
*
* uses table events
* @fields array(id, venue_id, ...)
*
*/
class Event extends AppModel {
public $name = "Event";
// setup the relationship to venues table with a counterCache
public $belongsTo = array(
'Venue' => array(
'className' => 'Venue',
'counterCache' => true
)
);
}
?>
<?php
/**
* Venue Model
*
* uses venues table
* @fields array(id, event_count, ...)
*
*/
class Venue extends AppModel {
public $name = "Venue";
// setup the relationship to events table
public $hasMany = array(
'Event' => array(
'className' => 'Event',
)
);
}
?>
<?php
/**
* Venues Controller
*
* example of a delete function using deleteAll to include conditions instead of delete which only takes an id
*
*/
class VenuesController extends AppController {
/**
* delete a venue
*
* checks to make sure a venue has no events and then deletes it.
*/
public function delete($id = null){
if($id){
// make sure the conditions array checks for event_count re: counterCache
$conditions = array('Venue.id' => $id, 'Venue.event_count' => 0);
// run deleteAll but enable callbacks so that the deleteAll functions as a normal delete
($this->Venue->deleteAll($conditions, true, true)) ? $this->Session->setFlash("Event deleted") : $this->Session->setFlash("Event still has attached events and could not be deleted.");
}
return $this->redirect(array('controller' => 'venues', 'action' => 'index'));
}
}
?>
0
我只是代码时,可能对场馆模型。
0
如果你正在使用InnoDB表,你可以添加防止场地被删除,如果有事件,如果场地ID进行更新,它会自动更新事件表的venue_id值的外键约束。
ALTER TABLE `events` ADD FOREIGN KEY ( `venue_id`) REFERENCES `venues` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE ;
或者类似的东西无论如何。
它只是一个选项,如果你想有补充说,在情况下,数据级别额外的鲁棒性有一个在您的应用程序,以防止在代码中被检测的限制的错误,你可以使用。我将它添加到代码中,以便您的应用程序不会收到SQL警告/错误。
相关问题
- 1. 实施
- 2. 实施中的jqGrid
- 3. 实施
- 4. Envers with Hibernate Interceptor,onDelete
- 5. 使用onDelete级联
- 6. Fortumo Android实施
- 7. FineUploader onDelete和的onComplete
- 8. 如何在Firebase中实现ondelete级联(Android)
- 9. 实施ListFragment
- 10. TCP国实施
- 11. PagerSlidingTabStrip实施
- 12. 实施的GetHashCode
- 13. 实施代码
- 14. @PreAuthorize:在实施
- 15. 实施的HttpWorkerRequest
- 16. GetIDsOfNames实施
- 17. MySQL FTS实施
- 18. iphone:实施
- 19. 实施FileTable
- 20. 实施的Android
- 21. 实施elasticsearch
- 22. 实施错误
- 23. stacklist实施
- 24. 实施NSOutlineView /每
- 25. Bookmarklet实施
- 26. 实施Login.xaml
- 27. producteev4j实施
- 28. CakePHP 3 - 已实现的事件() - 未触发已实施的事件
- 29. 实施促进
- 30. 实施字典