开发者

Add conditions to dependencys in CakePHP models? (or have dependent on multiple things together)

A User submits an Upload (like an image) of an Event to the website.

If EITHER the User OR the Event get deleted, the image should stay - but if BOTH the User AND the Event get deleted, the Upload should also be deleted.

Can this be done by setting CakePHP's dependent in the model? Can it be dependent on a combination of both things? Or - can I add 开发者_如何学JAVAconditions to the 'dependent'=>true ?

For example:

var User = array(
    'Upload' => array(
        'dependent' => true,
        //can I set a condition here? Or pass array w/ conditions to line above?
    ),
);

I'm fairly new to Cake, so if I've missed the boat - ie if there's another better way to do this, feel free to let me know.

My only thought so far is to just have it NOT dependent, and run the delete query myself w/ all needed conditions - but was hoping CakePHP would have something like this built in.


it would probably be best to do a bit of a check in afterDelete(), eg:

User::afterDelete(){
// if !$this->Event->find(...conditions...); delete the image
}

Event::afterDelete(){
// if !$this->User->find(...conditions...); delete the image
}

you could also use beforeDelete() with a check in a similar way, and if the conditions are met set 'dependent' dynamically through the relations

there is no way to set conditions on the 'dependent' option of the params


When calling the delete method in your model, set the second option to true.

Use BeforeDelete/AfterDelete methods in your model in conjunction with http://book.cakephp.org/view/1036/delete

delete(int $id = null, boolean $cascade = true);

Deletes the record identified by $id. By default, also deletes records dependent on the record specified to be deleted.

For example, when deleting a User record that is tied to many Recipe records (User 'hasMany' or 'hasAndBelongsToMany' Recipes):

if $cascade is set to true, the related Recipe records are also deleted if the models dependent-value is set to true.
if $cascade is set to false, the Recipe records will remain after the User has been deleted.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜