CakePHP - delete cascade not working

前端 未结 3 993
小鲜肉
小鲜肉 2021-01-06 13:50

In CakePHP I have a model Type and SpecificType.

SpecificType belongTo a Type. (type_id field)

When I delete an entry of SpecificType, how can I also delet

3条回答
  •  一个人的身影
    2021-01-06 14:15

    I had the same problem in a situation where I did not want to follow the Cake model key convention.

    I set the SpecificType model's belongsTo relationship to Type like so:

    public $belongsTo = array(
      'Type' => array(
        'className' => 'Type',
        'foreignKey' => 'type_id',
        'conditions' => '',
        'fields' => '',
        'order' => '',
      ),
    );
    

    Then to get cascading delete to work, I added the following to the SpecificType model:

    public function beforeDelete($cascade) {
      // Make sure the parent method runs.
      $continue = parent::beforeDelete($cascade);
    
      if ($continue) {
        // Delete the Type if there is one.
        $typeId = $this->field('type_id');
        if (!empty($typeId)) {
          $continue = $this->Type->delete($typeId);
        }
      }
    
      return $continue;
    }
    

    I hope that helps someone who has the same problem you had as I'm sure you're not still waiting for an answer.

提交回复
热议问题