2012-09-22 20 views
5

I mapping many-to-many sono facili da utilizzare in Redbean con scenari semplici. Ma come si fa la mappatura molti a molti tra lo stesso oggetto?Redbean, Multiple many-to-many utilizzando lo stesso oggetto

Esempio:

Quello che voglio compire è in struttura molto simile alla configurazione Twitter/instagram di "seguaci" e "dopo"

// this c 

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

// .. 

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

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

Ora, voglio, dal punto di vista user1 , elenca sia i follower che i seguenti utenti.

Tuttavia, non posso elencare i "follower", senza interrogare tutti gli utenti nel database e cercare user1. Esiste un modo per avere più elenchi "condivisi" in redbean o una buona soluzione per questi casi particolari o la query è la strada da percorrere?

risposta

6

Ecco il codice che uso con il test per dimostrare che funziona :)

<?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) 
----------------------------------- 
*/ 
Problemi correlati