laravel эквивалентный порядок случайным образом - PullRequest
1 голос
/ 14 июля 2020

Я новичок в 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();
    }

как я могу сделать добавьте к этому коду «ORDER BY RAND ()» из традиционного mysql?

Помогите, пожалуйста

1 Ответ

1 голос
/ 14 июля 2020

Laravel имеет метод inRandomOrder(), вызовите его в построителе запросов. Внизу капота для заказа будет использоваться после .

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