在我的情况下,我有两个表,如用户表和评级表。
在用户表中,我正在存储用户的个人详细信息,例如姓名,电子邮件等,
在评级表中,我正在存储 user_id和评级(评分将在1,2,3,4和5之类的数字中)
我创建了两个关系表 这是关系
//User Model
public function ratings()
{
return $this->hasMany(Rating::class);
}
//Rating model
public function user()
{
return $this->belongsTo(Consultant::class);
}
我能够以急切加载显示获取数据
$data = User::with('ratings')->get();
我将从急切的负载获得的响应是
[
{
"id": 1,
"cunsultant_name": "Quincy Jerde",
"contact_number": "882-904-3379",
"ratings": [
{
"user_id": 1,
"rating_for_user": 3
},
{
"user_id": 1,
"rating_for_user": 5
},
{
"user_id": 2,
"rating_for_user": 3
}
]
},
{
"user_name": "Alene Dicki",
"contact_number": "247.604.8170",
"ratings": [
{
"id": 4,
"user_id": 3,
"rating_for_user": 3
}
]
}
]
那么如何为每个急切加载的用户获得平均评分呢?
答案 0 :(得分:5)
要获得平均评分,您可以执行
$user->ratings()->avg('rating_for_user');
答案 1 :(得分:1)
这将始终在产品中附加average_rating字段。我使用变体关系进行评级,但是您可以使用适合您情况的任何关系。
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Product extends Model
{
protected $guarded = [];
protected $appends = ['average_rating'];
public function ratings()
{
return $this->morphMany(Rating::class, 'rateable');
}
public function getAverageRatingAttribute()
{
return $this->ratings()->average('value');
}
}
答案 2 :(得分:0)
你可以这样做,
$data = User::with('ratings')
->join('Rating table','user.id','=','Rating table.user_id')
->select('user.*',DB::raw('avg(rating_for_user)'))
->get();
根据需要修改代码。
我希望它有所帮助。
答案 3 :(得分:0)
您可以获得这样的平均评分,
$product=Products::where('id',$productid);
$data=$product->with('ratings')->get();
foreach($data as $d) {
return $d->ratings->avg('rating');
}
我添加了产品平均评级的代码,其中两个模型如下:
产品型号:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\URL;
class Products extends Model {
protected $table = "products";
public $timestamps = false;
public function ratings()
{
return $this->hasMany("App\Model\Reviews","p_id");
}
}
查看模型:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Reviews extends Model
{
protected $table = "product_reviews";
public $timestamps = false;
//Rating model
public function products()
{
return $this->belongsTo("App\Model\Products");
}
}
答案 4 :(得分:0)
如果您想获得多个用户的评分,可以这样做。
$users = User::where('type', 'instructor')->get();
foreach ($users as $user) {
$user['ratings'] = $user->ratings()->avg('rate');
}
return $users;