-2

こんにちは、ユーザーが相互にフォローできるように、私のウェブサイトにフォロー機能を作成しようとしています。私は Cakephp を使用しています。

注意: user_id と follower_id を含む user テーブル + follow テーブルを作成しました!

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 に答える