我想问你。希望我的问题能很快得到解决。
我有3个表格包括:
广告
ID
title_ads
交易
ID
的transaction_id
id_ads
的评价
关系:
广告到交易有很多
交易到评级属于
我想问一下,如何从表格广告中获得平均评分值?我很困惑,因为我认为获得平均评级可能使用hasManyThrought但在这种情况下,有关系属于。我解决了吗?非常感谢你:))
答案 0 :(得分:-1)
在hasManyThrough
模型中定义Ad
关系
class Ad extends Model
{
/**
* Get all ratings of an Ad.
*/
public function ratings()
{
return $this->hasManyThrough('App\Rating', 'App\Transaction');
}
}
现在,您可以使用Ad
模型和ratings
关系
public function getRatingsAverage()
{
// Fetch a single ad (or remove the find and get multiple)
$ad = Ad::where('id', 1)->with('ratings')->get();
// write average logic here...
// could be something like this:
$total_rating = 0;
foreach($ad->ratings as $rating) {
// loop through all the ratings of the ad and add the value to the total rating
$total_rating = $total_rating + $rating->value;
}
// divide the total rating by the amount of ratings to get the average
$average = $total_rating / count($ad->ratings);
}
答案 1 :(得分:-1)
要获得每个广告的评分,您可以通过急切加载关系来查询广告。然后,您可以循环浏览$ads
并添加平均逻辑来访问交易和评级。
$ads = Ads::with('transaction.rating')->get();
//Load all ads with the transaction and rating relations
foreach($ads as $ad){
//All transactions from the ad
$transactions = $ad->transaction;
foreach($transactions as $transaction){
//The rating from the transaction
$rating = $transaction->rating;
}
}