【问题标题】:laravel equivalent order by randomlaravel 等价顺序随机
【发布时间】:2020-07-14 10:28:46
【问题描述】:

我是 Laravel 的初学者。

我在 Laravel 7 中有项目。

我有这个代码:

public function getPromoProducts()
    {
        return $this->model->select('name', 'slug', 'products.id', 'small_description', 'promo_desc')->with(['features', 'frontImage'])->active()->leftJoin('selected_product_features', function ($join) {
            $join->on('products.id', '=', 'selected_product_features.product_id');
        })->where('selected_product_features.key', 'price_promo')->where('selected_product_features.description', '<>', 0)->limit(2)->get();
    }

如何从传统的 mysql 添加到此代码“ORDER BY RAND()”?

请帮帮我

【问题讨论】:

标签: php laravel laravel-5 laravel-7


【解决方案1】:

Laravel 有 inRandomOrder() 方法,在查询生成器上调用它。在引擎盖下,它将使用following 进行订购。

return $this->model->select('name', 'slug', 'products.id', 'small_description', 'promo_desc')
    ->with(['features', 'frontImage'])
    ->active()
    ->leftJoin('selected_product_features', function ($join) {
        $join->on('products.id', '=', 'selected_product_features.product_id');
    })->where('selected_product_features.key', 'price_promo')
    ->where('selected_product_features.description', '<>', 0)
    ->limit(2)
    ->inRandomOrder()
    ->get();

【讨论】:

  • return $this->model->select('name', 'slug', 'products.id', 'small_description', 'promo_desc') ->with(['features', ' frontImage']) ->active() ->leftJoin('selected_product_features', function ($join) { $join->on('products.id', '=', 'selected_product_features.product_id'); }) -> where('promo_desc', '', 0) ->limit(2) ->inRandomOrder() ->get(); - 它的工作:) 有时我有 2 个重复的产品。可以修复吗?
  • 使用 distinct('products.id') 我认为会有所帮助
猜你喜欢
  • 2017-05-12
  • 2020-11-12
  • 2012-11-19
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多