在简单情况下,多对多映射很容易在redbean中使用。但是,如何在同一个对象之间进行多个多对多映射?

例子:

我要完成的内容与“关注者”和“关注者”的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中有多个“共享”列表,或者有什么不错的解决方法,还是查询方式呢?

最佳答案

这是我与测试一起使用以证明其有效的代码:)

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

10-08 06:48