开发者

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

email

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:

  1. User hasMany Dress
  2. User hasMany Like
  3. Like belongsTo User
  4. Like belongsTo Dress
  5. Dress hasMany Like
  6. 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',
            )
    );
}
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜