-2

我正在尝试为我的网站创建一个关注功能,以便用户可以互相关注,我正在使用 Cakephp 我应该使用什么样的关系,我应该给表格命名。

注意:我创建了一个包含 user_id 和 follower_id 的用户表 + 关注表!

4

2 回答 2

2

如果您不需要保存有关关系的任何信息,那么 hasAndBelongsToMany 是在这种情况下使用的自然关系。尝试这个:

// User Model
var $hasAndBelonsToMany = array(
    'Follower' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'follower_id'
        'joinTable' => 'followers_users'
    )
)

那么您必须像往常一样创建 users 表,并创建一个包含'followers_users'列的表:'id', 'user_id', 'follower_id'(如果需要的话)。'created''updated'

编辑: 要检索您的数据(在此处阅读),您照常进行:

$this->User->find('all', array('conditions' => array('id' => 1)));

然后你会得到一个像这样的数组:

Array(
    [User] => array(
        [id] => 1
        [name] => xxxx
    )
    [Follower] => array(
        [0] => array(
            [id] => 2
            [name] => yyyy
        )
        [1] => array(
            [id] => 3
            [name] => zzzz
        )
    )
)

要保存数据(在此处此处阅读),您需要创建一个数组,例如:

array(
    [User] => array(
        [id] => 1
        [name] => xxx
    )
    [Follower] => array(
        [0] => array(
            [id] => 2
        )
        [1] => array(
            [id] => 3
        )
    )
)
于 2012-09-03T23:50:37.287 回答
0

书中对您正在查看的内容/示例的解释是正确的:

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#multiple-relations-to-the-same-model

每本书的类似示例:

“也可以创建自我关联,如下所示:”

<?php
class Post extends AppModel {
    public $name = 'Post';

    public $belongsTo = array(
        'Parent' => array(
            'className' => 'Post',
            'foreignKey' => 'parent_id'
        )
    );

    public $hasMany = array(
        'Children' => array(
            'className' => 'Post',
            'foreignKey' => 'parent_id'
        )
    );
}
于 2012-09-03T21:12:58.633 回答