2012-09-03 65 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