I have two tanulky stars and videos and relationships in the model
// in Star model
public function videos()
{
return $this->belongsToMany(Video::class);
}
and
// in Video model
public function user()
{
return $this->belongsTo(User::class);
}
If I do $stars = Star::with('videos')->get();
, the actor (stars) and the movies he starred in (videos) will be listed. I am attaching a json sample.
[{"id":1,"name":"Marek","videos":
[{"id":2,"user_id":1,"title":"ferwg","visitors":94,"pivot":{"star_id":1,"video_id":2}},
{"id":3,"user_id":1,"title":"fgtf","visitors":17,"pivot":{"star_id":1,"video_id":3}}
]}...
I have a visitors item in the videos table.How can I find out the total number of visitors for each actor (stars) for the movies he/she starred in?
My Answer:
You can achieve this by using Laravel's Eloquent relationships and querying capabilities. Here's how you can find the total number of visitors for each actor (star) for the movies he/she starred in:
php
$stars = Star::with('videos')->get();
foreach ($stars as $star) {
$totalVisitors = 0;
foreach ($star->videos as $video) {
$totalVisitors += $video->visitors;
}
echo "Total visitors for " . $star->name . ": " . $totalVisitors . "\n";
}
This code will loop through each star, then loop through each video for that star and calculate the total number of visitors for all the videos. Finally, it will output the total number of visitors for each star.
You can also optimize this query by using Laravel's `withCount` method to eager load the count of visitors for each video:
php
$stars = Star::with(['videos' => function ($query) {
$query->select('id', 'star_id', 'visitors')->withCount('visitors');
}])->get();
foreach ($stars as $star) {
$totalVisitors = $star->videos->sum('visitors_count');
echo "Total visitors for " . $star->name . ": " . $totalVisitors . "\n";
}
This code will load the count of visitors for each video using `withCount` and then calculate the total number of visitors for each star using the `sum` method.
Rate this post
4 of 5 based on 6306 votesComments