gpt4 book ai didi

mysql - 优化 Eloquent 关系检索

转载 作者:行者123 更新时间:2023-11-30 21:32:28 25 4
gpt4 key购买 nike

我有一个界面可以显示平台上的社区列表。社区有成员,反过来成员/个人资料可以彼此成为 friend 。在列表页面上,每个社区卡片都需要显示成员数量(社区中)和来自这些成员的 friend 数量(登录个人资料的 friend )。

这是一张社区卡的示意图

enter image description here

我首先与成员建立社区:

$communities = $loggedInProfile->communities->load('members')->take(15);

然后遍历社区和成员,找出哪些是登录用户的好友。

   foreach ($communities as $key => $community) {
$friends = [];
foreach ($community->members as $member) {
if ($loggedInProfile->isFriendWith($member)) {
array_push($friends, $member);
}
}
$community->members_who_are_friends = $friends;
}

我的问题是,当关联变大时,这在查询数量方面非常繁重。有没有更好的方法来检索这些关系而不必使用嵌套 for 循环?我还使用 Elasticsearch 为所有数据编制索引。使用 Elasticsearch 进行此类检索会更好吗?这也是 hasThrough 的一个很好的用例吗?

更新

成员关系:

public function members()
{
return $this->belongsToMany('App\Profile', 'community_members', 'community_id', 'profile_id')->withTimestamps();
}

isFriendWith 关系:

public function isFriendWith(Model $recipient)
{
return $this->findFriendship($recipient)->where('status', Status::ACCEPTED)->exists();
}

检查是在名为friendships 的表上完成的。检查 status 列(可以是 0 或 1)以查看是否是 friend 。

findFriendship 检查:

private function findFriendship(Model $recipient)
{
return Friendship::betweenModels($this, $recipient);
}

数据库结构:

-配置文件迁移

Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});

-社区迁移(外键为社区的owner)

Schema::create('communities', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('profile_id');
$table->foreign('profile_id')->references('id')->on('profiles');
$table->string('slug')->unique();
});

-社区成员迁移

Schema::create('community_members', function (Blueprint $table) {
$table->primary(['profile_id', 'community_id']);
$table->unsignedInteger('profile_id');
$table->foreign('profile_id')->references('id')->on('profiles');
$table->unsignedInteger('community_id');
$table->foreign('community_id')->references('id')->on('communities');
$table->timestamps();
});

-友情迁移

Schema::create('friendships'), function (Blueprint $table) {
$table->increments('id');
$table->morphs('sender');
$table->morphs('recipient');
$table->tinyInteger('status')->default(0);
$table->timestamps();
});

最佳答案

在你的行中:

$communities = $loggedInProfile->communities->load('members')->take(15);

load() 用于执行 Lazy Eager 加载,即在检索到社区后加载成员,从而对每个社区产生不同的查询。您可以使用 with() 通过单个查询提取全部数据。此外,take(15) 是在生成的集合上执行的,而不是在查询上执行的。试试这个:

$communities = $loggedInProfile->communities()->with('members')->take(15)->get();

关于mysql - 优化 Eloquent 关系检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55493561/

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