Как я могу вытащить все свои продукты и усреднить отзывы о продукте в Laravel? - PullRequest
0 голосов
/ 17 января 2019
$product = DB::table('product_list')->join('product_categories', 'product_list.product_category', '=', 'product_categories.id')
    ->join('product_types', 'product_list.product_type', '=', 'product_types.id')
    ->where('product_list.id', (int) $productId)
    ->get()
    ->first();

Который получает правильный продукт, который проходит по маршруту

Route::get('/products/{productId}', 'ProductController@single')->name('Single Product');

Проблема в том, что у меня есть таблица product_reviews, которая имеет отношение к таблице product_list.

public function up()
{
    Schema::create('product_reviews', function(Blueprint $table) {
        $table->increments('id');

        $table->integer('user_id')->unsigned();
        $table->integer('product_id')->unsigned();

        $table->string('review')->default('No comment was made on this product.');
        $table->integer('stars')->default(0);

        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

        $table->index(array('user_id', 'product_id'));

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('product_id')->references('id')->on('product_list');
    });
}

Отзывы пользователей хранятся в отдельной таблице, которая product_id относится к id из $product, полученного мной из БД.

Я пытаюсь получить оценку AVG() из всех этих stars на основе идентификатора продукта. Я пытался

$stars = DB::table('product_reviews')->selectRaw('AVG(stars)')
    ->whereColumn('product_id', 'product_list.id');

$product = DB::table('product_list')->join('product_categories', 'product_list.product_category', '=', 'product_categories.id')
    ->join('product_types', 'product_list.product_type', '=', 'product_types.id')
    ->selectSub($stars, 'stars_avg')
    ->where('product_list.id', (int) $productId)
    ->get()
    ->first();

Но я получаю этот вывод

{#631 ▼
  +"stars_avg": 5.0000
}

Вместо всей информации о моем продукте, добавлен дополнительный столбец stars_avg. Как я могу выделить все мои внутренние объединения с этим дополнительным столбцом сверху?

1 Ответ

0 голосов
/ 17 января 2019

Мне удалось это исправить, сначала запросив мои данные, прежде чем выбрать подзапрос. Я также добавил ROUND() к запросу, чтобы остановить null встречи и округлить значение до ближайшего 10.

$stars = DB::table('product_reviews')->selectRaw('ROUND(AVG(stars))')
        ->whereColumn('product_id', 'product_list.id');

$product = DB::table('product_list')->join('product_categories', 'product_list.product_category', '=', 'product_categories.id')
        ->select('*')
        ->selectSub($stars, 'stars_avg')
        ->join('product_types', 'product_list.product_type', '=', 'product_types.id')
        ->where('product_list.id', (int) $productId)
        ->take(1)
        ->get()
        ->first();

Это теперь дает мне желаемый результат:

{#634 ▼
  +"id": 3
  +"cost": "150.00"
  +"product_category": 1
  +"product_type": 3
  +"product_score": 0
  +"created_at": "2019-01-16 16:34:29"
  +"updated_at": "2019-01-16 16:34:29"
  +"rating": 0
  +"down_payment": "10.00"
  +"title": "Static"
  +"price_start": "50.00"
  +"price_stop": "150.00"
  +"theme": "Custom"
  +"pages": 4
  +"rbac": 0
  +"portal": 0
  +"external_software": 0
  +"company_supplier": "Iezon Solutions"
  +"stars_avg": "5"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...