简体   繁体   English

Laravel从表中选择随机ID

[英]Laravel select random id from table

i want to select random id from inserted data into table by this code, this code work fine when i dont have deleted row(s) from table, how can i manage or skip deleted row(s) on this part of code: 我想通过此代码从插入到表中的数据中选择随机id,当我没有从表中删除行时,此代码可以正常工作,如何在此部分代码上管理或跳过已删除的行:

rand($minId, $maxId)

code: 码:

$minId = DB::table('channel_image_container')->min('id');
$maxId = DB::table('channel_image_container')->max('id');

while (!$c = DB::table('channel_image_container')->find(rand($minId, $maxId))) {
}

echo json_encode([
    'path' => 'images/' . $c->file_name,
    'content' => $c,
    'parent' => DB::table('channel_content_type')->where('id', $c->content_id)->first()
]);

this part of code is best solution? 这部分代码是最佳解决方案?

while (!$c = DB::table('channel_image_container')->find(rand($minId, $maxId))) {
}

I would take advantage of inRandomOrder() (Laravel >= 5.2) : 我会利用inRandomOrder() (Laravel> = 5.2)

$c = DB::table('channel_image_container')->inRandomOrder()->first();

echo json_encode([
    'path' => 'images/' . $c->file_name,
    'content' => $c,
    'parent' => DB::table('channel_content_type')->where('id', $c->content_id)->first()
]);

You will need to take it like so: 您将需要像这样:

$c = DB::table('channel_image_container')->take(1)->inRandomOrder()->get();

echo json_encode([
    'path' => 'images/' . $c->file_name,
    'content' => $c,
    'parent' => DB::table('channel_content_type')->whereId($c->content_id)->first()
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM