gpt4 book ai didi

php - Laravel Eloquent Join vs Inner Join?

转载 作者:IT老高 更新时间:2023-10-28 23:50:37 24 4
gpt4 key购买 nike

所以我在弄清楚如何执行提要样式的 mysql 调用时遇到了一些麻烦,我不知道它是一个 Eloquent 问题还是一个 mysql 问题。我相信这两者都是可能的,我只是需要一些帮助。

所以我有一个用户,他们转到他们的提要页面,在这个页面上它显示了他们 friend 的东西( friend 投票、 friend 评论、 friend 状态更新)。假设我有 tom、tim 和 taylor 作为我的 friend ,我需要获得他们所有的投票、评论和状态更新。我该怎么做?我有一个按 ID 编号列出的所有 friend 的列表,并且我有每个事件(投票、评论、状态更新)的表,这些表中存储了 ID 以链接回用户。那么我如何才能一次获得所有这些信息,以便我可以将其显示在提要中。

蒂姆评论“酷”

Taylor 说“Woot first status update~!”

Taylor 投票选出了“有史以来最好的比赛”

编辑@damiani所以在完成模型更改后,我有这样的代码,它确实返回了正确的行

$friends_votes = $user->friends()->join('votes', 'votes.userId', '=', 'friend.friendId')->orderBy('created_at', 'DESC')->get(['votes.*']);
$friends_comments = $user->friends()->join('comments', 'comments.userId', '=', 'friend.friendId')->orderBy('created_at', 'DESC')->get(['comments.*']);
$friends_status = $user->friends()->join('status', 'status.userId', '=', 'friend.friendId')->orderBy('created_at', 'DESC')->get(['status.*']);

但我希望它们全部同时发生,这是因为 mysql 按顺序对数千条记录进行排序比 php 获取 3 个列表、合并它们然后执行它快 100 倍。有什么想法吗?

最佳答案

我确信还有其他方法可以实现此目的,但一种解决方案是通过查询生成器使用 join

如果你有像这样设置的表:

users
id
...

friends
id
user_id
friend_id
...

votes, comments and status_updates (3 tables)
id
user_id
....

在您的用户模型中:

class User extends Eloquent {
public function friends()
{
return $this->hasMany('Friend');
}
}

在你的 friend 模型中:

class Friend extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}

然后,要收集 id 为 1 的用户的 friend 的所有投票,您可以运行此查询:

$user = User::find(1);
$friends_votes = $user->friends()
->with('user') // bring along details of the friend
->join('votes', 'votes.user_id', '=', 'friends.friend_id')
->get(['votes.*']); // exclude extra details from friends table

commentsstatus_updates 表运行相同的 join。如果您希望投票、评论和 status_updates 位于一个按时间顺序排列的列表中,您可以将生成的三个集合合并为一个,然后对合并后的集合进行排序。


编辑

要在一个查询中获得投票、评论和状态更新,您可以构建每个查询,然后合并结果。不幸的是,如果我们使用 Eloquent hasMany 关系(see comments for this question 用于讨论该问题),这似乎不起作用,因此我们必须修改查询以使用 where 相反:

$friends_votes = 
DB::table('friends')->where('friends.user_id','1')
->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments =
DB::table('friends')->where('friends.user_id','1')
->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates =
DB::table('status_updates')->where('status_updates.user_id','1')
->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events =
$friends_votes
->union($friends_comments)
->union($friends_status_updates)
->get();

不过,在这一点上,我们的查询变得有点复杂,所以多态关系和一个额外的表(如下面建议的 DefiniteIntegral)可能是一个更好的主意。

关于php - Laravel Eloquent Join vs Inner Join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25984226/

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