2010-09-03 61 views
1

限制结社我有事件属于关联地点关联。 当用户试图删除场地时,我不希望在一个或多个事件与其关联时发生。 什么是最自动的方式来做到这一点?实施ondelete CakePHP中

回答

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

如果你正在使用InnoDB表,你可以添加防止场地被删除,如果有事件,如果场地ID进行更新,它会自动更新事件表的venue_id值的外键约束。

ALTER TABLE `events` ADD FOREIGN KEY ( `venue_id`) REFERENCES `venues` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE ; 

或者类似的东西无论如何。

它只是一个选项,如果你想有补充说,在情况下,数据级别额外的鲁棒性有一个在您的应用程序,以防止在代码中被检测的限制的错误,你可以使用。我将它添加到代码中,以便您的应用程序不会收到SQL警告/错误。