laravel获取特定记录的行号

时间:2020-10-17 14:07:29

标签: mysql laravel

我有一张桌子queue,我想知道user在哪个位置或行号。

队列表

----------------------------------------------------
| id  |  name  |        created_at       |   done  |
+-----+--------+-------------------------+---------+
|  1  |  John  |   2020-10-17 01:08:59   |    1    |
|  2  |  Jane  |   2020-10-17 01:10:15   |    0    |
|  3  |  Jess  |   2020-10-17 01:18:15   |    0    |
|  4  |  Joe   |   2020-10-18 08:18:15   |    0    |
|  5  |  Moe   |   2020-10-18 11:18:15   |    0    |
----------------------------------------------------

是否可以知道queue中的特定用户数?例如Jess将返回3,因为他是队列记录中的3rd用户。

编辑:例如John在队列中完成,现在Jess将成为队列中的2nd

2 个答案:

答案 0 :(得分:3)

我想我有办法:

主要思想是根据其id值获取前一个队列的计数, 诀窍是在主表中使用别名,以便您可以在内部选择中使用该别名。

   $values = DB::table('queue', 'u1')
            ->select('u1.id',DB::raw("((SELECT count(*) from queue WHERE queue.id < u1.id)+1) rowNumber"))
            ->orderBy('u1.id')
            ->get();

编辑:

如果要排除已完成的队列,则应在主选择器和内部选择器中执行:

 $values = DB::table('queue', 'u1')
            ->select('u1.id',DB::raw("((SELECT count(*) from queue WHERE (queue.id < u1.id)and(queue.is_done!=1) )+1) rowNumber"))
            ->where('u1.is_done','!=',1)
            ->orderBy('u1.id')
            ->get();

答案 1 :(得分:-1)

如果您不需要直接通过查询获取该号码,则可以 search()

$collection->search(function ($item, $key) {
    return $item->name == 'Jess';
});