【问题标题】:Laravel Eloquent - take results randomly from whereInLaravel Eloquent - 从 whereIn 随机获取结果
【发布时间】:2020-01-15 13:59:35
【问题描述】:

Laravel 4.2 版

我遇到了这个问题。 我需要填写 5 个结果的配额,但是我的数组大小只有 3。我还需要从数组中随机选择行。

*edit: 获取所有结果是不可行的

    $store_id_array = array('111', '222' , '333');

    $reviews = Review::whereIn('store_id', $store_id_array)
                      ->take(5)
                      ->get();

    return Response::json($reviews);

这将返回 5 个结果,但仅来自数组中的第一项。 如何从数组项中随机选择?

【问题讨论】:

  • @thmpl 可能是遗留代码,没有升级预算。与 Laravel 保持同步是一个很好的建议,但并非总是可行。

标签: php laravel eloquent


【解决方案1】:

对于低于版本 5 的 Laravel:

orderBy(DB::raw('RAND()')) 像这样:

$reviews = Review::whereIn('store_id', $store_id_array)
                      ->orderBy(DB::raw('RAND()'))
                      ->take(5)
                      ->get();

对于 Laravel 5.0 +

使用inRandomOrder()方法:

$reviews = Review::whereIn('store_id', $store_id_array)
                      ->inRandomOrder()
                      ->take(5)
                      ->get();

【讨论】:

  • 这仍然只会随机排序来自“111”的结果,而不是从数组中的完整列表中随机排序,感谢您的贡献。
  • 这个查询应该有效。是否有可能您的数据库中有太多带有 store_id 111 的记录,因此没有足够的 222333 来持续检索?
  • 这与查询 select * from review where store_id in (111, 222, 333) order by RAND() limit 5 相同,这应该是您想要的。
【解决方案2】:
     public function index()
        {
           $categories = Category::latest()->get();
           $protfolios = Protfolio::all();
 $randompost = Post::approved()->publish()->take(4)->InRandomOrder()->get();
            $allposts = Post::where('price', 0)->approved()->publish()->take(8)->get();
            $posts = Post::latest()->where('price', '>=', 0)->approved()->publish()->take(8)->get();

            $latestposts = Post::latest()->approved()->publish()->take(8)->get();
            return view('welcome',compact('posts','randompost ','categories','allposts','latestposts','protfolios'));
        }

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2018-03-13
    • 2021-08-30
    • 2012-09-03
    • 1970-01-01
    • 2014-01-03
    • 2019-09-10
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多