我知道这似乎是一个记录在案的 mySQL 问题。但是,我发现没有 Eloquent 解决方案来获取 orderBy 查询中的行的排名。这就是我想要的。
我有一个看起来像这样的表
id | number
-----------
1 | 30
2 | 24
3 | 4
4 | 45
我可以对这个查询的数字列进行排序:
Number::orderBy('number', 'desc')->get();
但是,我想检索每一行的排名。因此,id 为 4(编号为 45)的行的排名为 1。id 为 1(编号为 30)的行的排名为 2。
使用 Eloquent 查询获取行排名的最佳方法是什么?
最佳答案
对于 laravel 的 Eloquent... 将其添加到您的模型中。释放 T.Otwells Eloquent 的伟大 ;)
public function getPostionAttribute()
{
return $this->newQuery()->where('number', '>=', $this->number)->count();
}
关于php - 在 OrderBy Eloquent 查询中获取行的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24621136/