Delete a belongsTo Association
There's surprisingly little information to be found about this and I guess I've never run开发者_开发技巧 into it before, but I'm in a situation where I have a model with a belongsTo
relationship. The model is the key and when I delete a record, I need to ensure that its associated record is also deleted.
Specifically, I have a Building
model that belongsTo
an Address
. When I delete the building, I need to be sure that the associated address is also deleted.
I can't flag the association as dependent, of course, so is a callback the best way to ensure that the address record gets deleted or is there a better way? This is one of those cases where I know I can do it with a callback, but at a visceral level, it seems like there should be a better way. I'm wondering whether that's the case.
Thanks.
why not using Foreign Keys in the database and select on DELETE CASCADE
and let the database do the work...
[Based on the comment] if you the Address is attached to other models that you dont want to delete, you can set those FK to ON DELETE RESTRICT
and the building wont be deleted.
And if you need something more complex you can add the beforeDelete() callback in your model, there's an example in the doc
Good Luck
In cakephp 3.x you can use the unlink method like described here:
http://api.cakephp.org/3.3/class-Cake.ORM.Association.HasMany.html#_unlink
This would set the foreign key field in the database to null
In your case it should be something like this everytime when you want to delete records from buildings so integrate it in your delete function. Of course it requires properly associations in the models.
$address = $this->Addresses->get('address_id'):
$building = $this->Buildings->find()->where(['building_id' => 'some_id'])->toArray();
if ($this->Addresses->association('Buildings')->unlink($address, $building)) {
$this->Flash->success(__('Success!'));
return $this->redirect($this->referer());
} else {
$this->Flash->error(__('Error.'));
return $this->redirect($this->referer());
}
精彩评论