Relationships

Below you will find the types of models relationship you can have in CakePHP and a little explanation of how BrowniePHP acts regarding each type.

belongsTo

For example, Post belongsTo Cateogory. In this case, each time you add or edit a post, you will find in the form one category selector to indicate with category belongs to this post.

In addition to that, every time you see the category name in a posts listing or a post view, that category name will be a link to the view of the category.

You can also configure a search filter by category, and every other model that the model belongs to. See the filters section for more information.

hasOne

Doc under development

hasAndBelongsToMany

Doc under development

hasMany

For example, Category hasMany Post. In that case, when you are in the view of a Category you will find a list of every Post for that category, just like in the standard CakePHP scaffolding.

What happens on deletion

The most important issue to consider when dealing with hasMany relationships is what happens with the related models when I delete a parent model. Following our example, if you try to delete a category, you’ll find 3 possible scenarios.

You can’t delete the category

If the foreign key of the Post model (it would be the field category_id, if you follow Cake standards) cannot be null (it’s settled as not null in the database), you won’t be able to delete the category until every post is deleted or assigned to another category.

You can delete the category, and all posts of that category will have no category

If the foreign key of the Post model can be null, then all posts belonging to the category that is being deleted will be modified and saved as null.

The category and all its posts are deleted

If the relationship is dependent, that means, you set dependent => true in the hasMany array, the deletion of the category will trigger a cascade deletion of every post that belongsTo that category (this is native Cake functionality). In this case, it doesn’t matter if the foreign key can be null or not.


Next: Behaviors