CakePHP - Likes design (Relationship Types)
Im designing a dressess database/table where each user can post/have multiple dressess.
http://book.cakephp.org/view/1040/Relationship-Types
A user can have multiple dressess.
Many dresssess belong to a user.
My users table:
id
name
username
passwd
...
My dressess table:
id
name
image
user_id
...
Now i need to create relationships to handle user likes, where a user can likes his/her own dresses or other user dressess...
My question is, what kind Relationship Types (tables and connections) do I have to manage for this feature.
Please tell what do you think about:
likes
id user_id dress_id
But, then question is, which is the right way:
A. Many Likes belong to User and Many Likes belong to Dress.
B.开发者_开发技巧 A user can have multiple Likes and Many Likes belong to a User.
Thanks in advance.
You are almost correct. You missed "A Dress can have multiple likes" .
In your model association:
- User hasMany Dress
- User hasMany Like
- Like belongsTo User
- Like belongsTo Dress
- Dress hasMany Like
- Dress belongsTo User
Code should be like this:
<?php
class User extends AppModel {
var $name = 'User';
var $hasMany = array('Dress', 'Like');
?>
<?php
class Like extends AppModel {
var $name = 'Like';
var $belongsTo = array('User', 'Dress');
?>
<?php
class Dress extends AppModel {
var $name = 'Dress';
var $hasMany = array('Like', 'User');
?>
I have omitted other attributes. You can easily generate these relationships from bake.
try hasAndBelongsToMany Relation
<?php
class User extends AppModel {
var $name = 'User';
var $hasAndBelongsToMany = array(
'Dress' =>
array(
'className' => 'Dress',
'joinTable' => 'like',
'foreignKey' => 'user_id',
'associationForeignKey' => 'dress_id',
)
);
}
?>
精彩评论