In my ArticleController I have:
public function index()
{
$article= Article::with('ratingAvg')->get();
return view('article.index',['article' => $article]);
}
And in my Article model:
public function ratingAvg()
{
return $this->hasOne('App\Rating', 'article_id')
->selectRaw('article_id AVG(rating) as rating')
->groupBy('article_id');
}
In article.index :
@foreach ($article as $a)
<p>{{$a}}</p>
@endforeach
As a result I receive the following data from the database:
{"id":10,"name":"Article1","rating_avg":{"article_id":10,"rating":"4.0"}}
When running dd($article);
in the ArticleController I receive:
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"
]
}
]
}
]
}
My question is, how can I display the rating value from the rating_avg object?
Here:
$article = Article::with('ratingAvg')->get();
you are eager-loading this relation:
public function ratingAvg()
So you should access the relation in the view this way:
@foreach ($article as $a)
<p>{{ $a->ratingAvg->rating }}</p>
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.