Php 我怎样才能拿出我所有的产品,并在Laravel中对该产品的评论进行平均?
哪一个获得通过路线的正确产品Php 我怎样才能拿出我所有的产品,并在Laravel中对该产品的评论进行平均?,php,sql,laravel,laravel-5,pdo,Php,Sql,Laravel,Laravel 5,Pdo,哪一个获得通过路线的正确产品 $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('pro
$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();
问题是我有一个product\u reviews
表,它与product\u列表
表有关系
Route::get('/products/{productId}', 'ProductController@single')->name('Single Product');
用户评论存储在一个单独的表中,product\u id
与我从数据库获得的$product
的id
相关
我正试图根据产品ID从所有这些明星中获得AVG()
评级。我已经尝试过了
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');
});
}
但是我收到了这个输出
$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();
而不是我所有的产品信息,添加了一个额外的stars\u avg
列。如何在顶部显示这个额外列的所有内部联接?我通过在选择子查询之前先查询数据来解决这个问题。我还向查询中添加了ROUND()
,以停止null
遭遇,并将值四舍五入到最接近的10
{#631 ▼
+"stars_avg": 5.0000
}
现在,这为我提供了所需的输出:
$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"
}