php - Laravel 从表中选择随机 id

标签 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))) {
}

最佳答案

我会利用 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/

相关文章:

php - 如果数据库中没有记录,则分页错误

laravel - 如何在 laravel 5 中更改密码重置消息?

php - Laravel 将我的 CRUD 迁移到另一个项目

laravel - Vue 3,Uncaught TypeError : Vue. use is not a function

postgresql - 在 Laravel 中注册自定义 Doctrine DBAL 类型

Laravel Blade : What is best practice for adding javascript in blade files?

php - 安装chamilo期间发生 fatal error

php - 传递给 PDOStatement::bindParam() 的参数名称的前导冒号是可选的吗?

php - 是否有用于 PHP 的 'best' Google 图表 API?

php - 为什么我不应该在 PHP 中使用 mysql_* 函数?