Laravel从表中选择随机id

时间:2017-10-02 10:21:52

标签: php laravel

我想通过此代码从插入的数据中选择随机ID到表中,当我没有从表中删除行时,此代码工作正常,我如何管理或跳过这部分代码上的已删除行:

rand($minId, $maxId)

代码:

$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()
]);

这部分代码是最好的解决方案吗?

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

2 个答案:

答案 0 :(得分: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()
]);

答案 1 :(得分:1)

你需要这样做:

$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()
]);