Laravel查询订单inrandormorder查询

发布于 2025-01-21 10:12:55 字数 377 浏览 3 评论 0原文

我的桌子上有40行,我想要的是随机获取20行,然后按ID订购这5个列表;这2个查询;

例如,ID 1至40的范围;我从随机顺序15 10 14 9 3中获得;因此,在最终结果中,我希望得到3 9 10 14 15,

我尝试同时使用inrandomorder和orderby,

$query->inRandomOrder()->orderBy('id', 'asc')

但是inrandomorder查询总是对查询的最终执行;如果我切换他们的位置:

$query->orderBy('id', 'asc')->inRandomOrder()

订单始终具有最终执行

I have 40 rows in my table, what i want is to get 20 row randomly, and after order these 5 list by id; these 2 in one query;

for example in range of id 1 to 40; i get from the random order 15 10 14 9 3;so in the final result i expect to get 3 9 10 14 15

i tried to use inRandomOrder and orderBy in same time

$query->inRandomOrder()->orderBy('id', 'asc')

but the inRandomOrder query always has the final execution of my query; and if i switch their position:

$query->orderBy('id', 'asc')->inRandomOrder()

the orderBy always has the final execution

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2025-01-28 10:12:55

2我猜想,如果您仅操纵数十行行,则可以使用Laravel Collection订购ID您的查询结果。

只需使用:

$result = $query->inRandomOrder()->get();

$resultSortedById = $result->sortBy('id');

或使用SQL查询,您可以使用此查询:

SELECT * FROM
(
    SELECT * FROM table
    ORDER BY RAND()
    LIMIT 20
) result
ORDER BY id ASC

您可以直接以雄辩的方式或SQL进行翻译。

我不一定会理解您的问题,btw: 通过ID 订购这5个列表?你到底是什么意思?

2 solutions I guess, if you manipulate only dozens of rows, you can use Laravel collection to order by ID your query result.

Just use:

$result = $query->inRandomOrder()->get();

$resultSortedById = $result->sortBy('id');

Or using SQL query, you can use this query:

SELECT * FROM
(
    SELECT * FROM table
    ORDER BY RAND()
    LIMIT 20
) result
ORDER BY id ASC

You can translate in Eloquent way, or as SQL directly.

I am not sure to understand your question btw: order these 5 list by id ? What do you mean exactly ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文