gpt4 book ai didi

php - Redbean,多个多对多使用相同的对象

转载 作者:可可西里 更新时间:2023-11-01 14:04:09 25 4
gpt4 key购买 nike

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

例子:

我想要完成的是在结构上与“followers”和“following”的 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)
-----------------------------------
*/

关于php - Redbean,多个多对多使用相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12542102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com