使用laravel5.4从mysql获取随机元素

qhhrdooz  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(379)

我从测试表中随机显示一个元素,因此如何获取该元素的id:

$tests= DB::table('test')->inRandomOrder()->limit(1)->get();

因为我想把它和其他身份证比较一下

ecfdbz9o

ecfdbz9o1#

->get() 返回一个 Collection 或是你家的唱片 test table。您需要使用循环来比较单个记录的值:

$id = 1; // Or whatever you're comparing to
$tests = DB::table('test')->inRandomOrder()->limit(1)->get();
foreach($tests AS $test){ 
  dd($test->id == $id); 
}

或者干脆用 ->first() 从中返回单个记录 test :

$id = 1;
$test = DB::table('test')->inRandomOrder()->first();
dd($test->id == $id);
toiithl6

toiithl62#

->get(); 方法返回示例 \Illuminate\Database\Eloquent\Collection. 用于获取单个示例使用 ->first(); 方法。另见官方文件https://laravel.com/docs/5.5/queries#ordering-分组限制和偏移
例如。

$test = DB::table('test')->inRandomOrder()->first();
if ($test->id == $id) {
    // your logic
}

相关问题