获得平均嵌套关系属于laravel

问题描述:

我想问你。希望我的问题能很快得到解决。获得平均嵌套关系属于laravel

我有3个表包括:

广告

  • ID

  • title_ads

交易

  • ID

  • TRANSACTION_ID

  • id_ads

评级

  • ID
  • TRANSACTION_ID
  • RATING_VALUE

关系:

广告交易有许多

交易评级是属于

我要问这个,如何从表广告得到平均评分值?我很困惑,因为我认为获得平均评级也许使用hasManyThrought,但在这种情况下,有关系belongsTo。要解决它吗?非常感谢你:)

定义您Ad模型hasManyThrough关系

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); 
} 
+0

我可以有许多与关系belongsTo? –

+0

它有hasManyThrough或belongsTo。不是都。是的,你可以与另一个模型建立另一种关系。 – Liam

+0

好的。非常感谢你。我的问题已经完成。 –

要获取每个广告的评分,您可以通过加载关系来查询广告。然后,您可以循环访问$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; 
    } 
}