【发布时间】:2019-06-11 01:33:39
【问题描述】:
$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 与我从数据库中获得的$product 中的id 相关。
我正在尝试根据产品 ID 从所有这些 stars 中获得 AVG() 评级。我试过了
$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 列。我怎样才能用顶部的这个额外列显示我所有的内部连接?
【问题讨论】:
标签: php sql laravel laravel-5 pdo