gpt4 book ai didi

mysql - 根据外键表中的键对表进行排序

转载 作者:行者123 更新时间:2023-11-30 01:07:15 25 4
gpt4 key购买 nike

我有表用户和表

points有外键user_id,所以我在我的User Eloquent模型中这样做了:

public function points()
{
return $this->hasMany('Point', 'user_id');
}

现在我可以通过执行以下操作获得一个用户的积分:

$user->points()->count();

但我想要做的是根据所有用户赢得的积分对所有用户进行排序,然后按每页 20 个对用户进行分页。

最佳答案

您将从逆关系开始:

$points = Point::with('User')
->orderBy('votes', 'desc')
->skip($offset)
->take($page_size); // or use ->paginate();

然后在你看来:

@foreach($points as $point)
{{ $point->votes }} | {{ $point->user->name }}
@endforeach

注意:请确保在 Point 模型中定义逆关系。

关于mysql - 根据外键表中的键对表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19655382/

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