dongshuo8756 2018-03-23 03:50
浏览 443
已采纳

Laravel 5.6 inRandomOrder和OrderBy

How to take datas from Database like this. But randomly and never duplicate.

$questions = Question::orderBy("created_at", 'desc')->skip(0)->take(3)->get();
$inquiries = Question::orderBy("created_at", 'desc')->skip(3)->take(3)->get();
$queries = Question::orderBy("created_at", 'desc')->skip(6)->take(3)->get();
$examinations = Question::orderBy("created_at", 'desc')->skip(9)->take(3)->get();
$inquisitions = Question::orderBy("created_at", 'desc')->skip(12)->take(3)->get();

It works but duplicates.

$questions = Question::inRandomOrder()->limit(10)->get();
$inquiries = Question::inRandomOrder()->limit(10)->get();
$queries = Question::inRandomOrder()->limit(10)->get();
$examinations = Question::inRandomOrder()->limit(10)->get();
$inquisitions = Question::inRandomOrder()->limit(10)->get();
  • 写回答

1条回答 默认 最新

  • doulun0651 2018-03-23 04:03
    关注

    How about you get them all with 1 call and sort them with PHP using collection splice method:

    $all = Question::inRandomOrder()->limit(50)->get();
    
    $questions = $all->splice(0, 10);
    $inquiries = $all->splice(0, 10);
    $queries = $all->splice(0, 10);
    $examinations = $all->splice(0, 10);
    $inquisitions = $all->splice(0, 10);
    

    You could also just save IDs you've already pulled in an array and ignore those when doing new queries with ->whereNotIn() like this:

    $except = []; // We'll save IDs of those pulled already here
    
    $questions = Question::inRandomOrder()->limit(10)->get();
    $except = array_merge($except, $questions->pluck('id')->toArray()); // Add IDs from upper call
    
    // Add ->whereNotIn, to ignore IDs from $except
    $inquiries = Question::inRandomOrder()->whereNotIn('id', $except)->limit(10)->get(); 
    $except = array_merge($except, $inquiries->pluck('id')->toArray()); // Add IDs from upper call
    
    $queries = Question::inRandomOrder()->whereNotIn('id', $except)->limit(10)->get();
    $except = array_merge($except, $queries->pluck('id')->toArray()); // Add IDs from upper call
    
    $examinations = Question::inRandomOrder()->whereNotIn('id', $except)->limit(10)->get();
    $except = array_merge($except, $examinations->pluck('id')->toArray()); // Add IDs from upper call
    
    $inquisitions = Question::inRandomOrder()->whereNotIn('id', $except)->limit(10)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?