我想通过这段代码从插入的数据中选择随机 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))) {
}
最佳答案
我会利用 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()
]);
关于php - Laravel 从表中选择随机 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523705/