Laravel 5.6 inRandomOrder和OrderBy

时间:2018-03-23 03:50:11

标签: php laravel

如何从数据库中获取数据。但随机而且永远不会重复。

impl Atag {
    /// Returns `Some` if this is a `Core` ATAG. Otherwise returns `None`.
    pub fn core(self) -> Option<Core> {
        if let Atag::Core(_) = self {
            Some(self)
        } else {
            None
        }
    }
}

它有效但重复。

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

1 个答案:

答案 0 :(得分:1)

如何通过1次调用获取它们并使用集合splice方法对它们进行排序:

$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);

您还可以保存已经在数组中提取的ID,并在使用->whereNotIn()进行新查询时忽略这些ID:

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