2012-09-22 72 views
5

多對多映射在簡單場景中易於在Redbean中使用。但是,如何在同一個對象之間進行多對多映射?Redbean,使用相同對象的多對多多對多

例子:

我想acomplish是在結構上非常相似,「追隨者」的Twitter的/ Instagram的設置和「下面的」

// this c 

$user = R::dispense('user'); 
$user2 = R::dispense('user'); 

// .. 

//Usr1 follows user2 
$user->sharedUser[] = $user2; 

// user2 follows user1 
$user2->sharedUser[] = $user1; 

現在,我想,從USER1視角,列出追隨者和下列用戶。

但是,我無法列出「追隨者」,而無需查詢數據庫中的所有用戶並查找user1。有沒有辦法在redbean中有多個「共享」列表,或者針對這些特殊情況有什麼好的解決方法,或者是查詢方式嗎?

回答

6

這裏是我一起用與測試代碼來證明它的工作原理:)

<?php 
include_once 'rb.php'; 
R::setup(); 


//create users 
$users = array(); 
foreach (array('arul', 'jeff', 'mugunth', 'vish') as $name) { 
    $user = R::dispense('user'); 
    $user->name = $name; 
    $user->follows = R::dispense('follows'); 
    //create variables with specified names ($arul, $jeff, etc) 
    $$name = $user; 
    $users[] = $user; 
} 

//set relationships 
$arul->follows->sharedUser = array($jeff); 
$mugunth->follows->sharedUser = array($jeff, $arul); 
$vish->follows->sharedUser = array($arul, $mugunth); 

R::storeAll($users); 

//print relationships 
$id = 1; 
while (true) { 
    echo "-----------------------------------\n"; 
    $u = R::load('user', $id++); 
    if (!$u->id) break; 
    echo "$u->name follows " . count($u->follows->sharedUser) . " user(s) \n"; 
    if ($u->follows) { 
     foreach ($u->follows->sharedUser as $f) { 
      echo " - $f->name \n"; 
     } 
    } 
    echo "\n$u->name is followed by " 
     . R::getCell("SELECT COUNT(*) FROM follows_user WHERE user_id = $u->id") 
     . " user(s) \n"; 
    foreach ($u->sharedFollows as $f) { 
     $follower = array_shift($f->ownUser); 
     echo " - $follower->name \n"; 
    } 
} 

/* echos the following 
----------------------------------- 
jeff follows 0 user(s) 

jeff is followed by 2 user(s) 
    - arul 
    - mugunth 
----------------------------------- 
arul follows 1 user(s) 
    - jeff 

arul is followed by 2 user(s) 
    - mugunth 
    - vish 
----------------------------------- 
mugunth follows 2 user(s) 
    - jeff 
    - arul 

mugunth is followed by 1 user(s) 
    - vish 
----------------------------------- 
vish follows 2 user(s) 
    - arul 
    - mugunth 

vish is followed by 0 user(s) 
----------------------------------- 
*/