2012-09-03 147 views
-2

Hy我想创建一个跟随功能到我的网站,所以用户可以关注对方,我使用Cakephp我应该使用什么样的关系,我应该如何命名表。Cakephp多对多递归

注意:我创建了一个用户表+ follow表,其中包含user_id和follower_id!

回答

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' 
     ) 
    ); 
} 
2

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

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

则必须创建用户表正常,和一张桌子'followers_users'的列:'id''user_id''follower_id'(和'created''updated'如果需要的话)。

编辑: 要检索您的数据(读here)你做像往常一样:

$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 
     ) 
    ) 
) 

要保存数据(阅读herehere),您需要创建一个阵列:

array(
    [User] => array(
     [id] => 1 
     [name] => xxx 
    ) 
    [Follower] => array(
     [0] => array(
      [id] => 2 
     ) 
     [1] => array(
      [id] => 3 
     ) 
    ) 
) 
+0

我怎么可以检索添加数据? – sleimanx2

+0

检查编辑! ;) – Choma