2017-10-02 19 views
0

このコードでは、挿入されたデータからランダムなIDを選択したいのですが、このコードはテーブルから行を削除しないとうまく動作します。 )このコードの一部に: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

私は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

あなたがそうのようにそれを取る必要があります。

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

は ''(1)を取りますと 'first()'はほとんど同じことをします(この文脈では)。私はこの男がなぜ下降しているのか分からない。 – Andrew

+0

IDKでも、私はこのメソッドがget関数のためにローディング時に少なくとも0.5秒は良いと言うことができます。 – GabMic

+0

これは間違っているため、彼のロジックは1つのアイテムで動作し、コレクションを取得しています。このメソッドで失敗するプロパティにアクセスする。ここで確認できるように、https://imgur.com/a/goArL – aaron0207

関連する問題