こんにちは、ユーザーが相互にフォローできるように、私のウェブサイトにフォロー機能を作成しようとしています。私は Cakephp を使用しています。
注意: user_id と follower_id を含む user テーブル + follow テーブルを作成しました!
リレーションに関する情報を保存する必要がない場合は、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
)
)
)
あなたが探しているものの説明/例は本の中にあります:
本ごとの同様の例:
"以下に示すように自己関連付けを作成することもできます:"
<?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'
)
);
}