2012-09-22 7 views
5

シンプルなシナリオで多対多マッピングを簡単に使用できます。しかし、同じオブジェクト間で複数の多対多マッピングをどのように行うのですか?レッドビーン、複数の多対多オブジェクトを使用

例:私はacomplishたい何

は構造の「フォロワー」のさえずり/ Instagramのセットアップに非常に類似しており、user1の観点から、私がしたい、今すぐ

// this c 

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

// .. 

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

// user2 follows user1 
$user2->sharedUser[] = $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) 
----------------------------------- 
*/ 
関連する問題