在我的ArticleController中,我有:
public function index()
{
$article= Article::with('ratingAvg')->get();
return view('article.index',['article' => $article]);
}
在我的文章模型中:
public function ratingAvg()
{
return $this->hasOne('App\Rating', 'article_id')
->selectRaw('article_id AVG(rating) as rating')
->groupBy('article_id');
}
在article.index中:
@foreach ($article as $a)
<p>{{$a}}</p>
@endforeach
结果,我从数据库中收到以下数据:
{"id":10,"name":"Article1","rating_avg":{"article_id":10,"rating":"4.0"}}
dd($article);
在ArticleController中运行时,我收到:
Collection {#194 ▼
#items: array:2 [▼
0 => Article{#188 ▼
#table: "articles"
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:12 [▶]
#original: array:12 [▶]
#relations: array:1 [▼
"ratingAvg" => Rating {#195 ▼
#table: "ratings"
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [▼
"article_id" => 10
"rating" => "4.0"
]
}
]
}
]
}
我的问题是,如何显示rating_avg 对象的评分值?