KonstantinK
KonstantinK

Reputation: 787

CakePHP - MVC Model Associations - How can I structure this data model?

quick question that I have been stuck with since hours:

For my cakePHP website project (using version 2.0) I have 2 Models. They are a bit obscure so I'll translate the model to the standard blog post models.

So I have a "Posts" model and for those many "Categories".

class Post
$belongsTo = 'Category'

class Category
$hasMany = 'Post'

So far so good. Now I want every category to have exactly one (mandatory) 'main post'.

How would I associate that?

Please help me, [insert name]. You're my only hope. ;)

Edit: I guess it would be great if there was a way to have a "hasOne" relationship but have the foreign key in the same class that $hasOne X and not in the other as is standard.

Upvotes: 1

Views: 262

Answers (2)

Thiago Belem
Thiago Belem

Reputation: 7832

Here is one solution:

[ categories ]
id
name
mainpost_id

[ posts ]
id
category_id
title
text
  • Category hasMany Post
  • Post belongsTo Category
  • Category hasOne MainPost (see code)

Upvotes: 1

Kashif Khan
Kashif Khan

Reputation: 2645

i think you use hasAndBelongsToMany relationship....see more details at this link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

Upvotes: 0

Related Questions