"Laravel joins two tables and calculates the sum of the columns of the given related table"
P粉617597173
2023-09-05 16:22:37
<p>I have two tanulky stars and relationships in videos and models</p>
<p>//In the Star model</p>
<pre class="brush:php;toolbar:false;">public function videos()
{
return $this->belongsToMany(Video::class);
}</pre>
<p>and
// In the Video model</p>
<pre class="brush:php;toolbar:false;">public function user()
{
return $this->belongsTo(User::class);
}</pre>
<p>If I execute<code>$stars = Star::with('videos')->get();</code>, the actor (stars) and the movies he starred in (videos) will be listed ). I've attached a JSON example. </p>
<pre class="brush:php;toolbar:false;">[{"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}}
]}...</pre>
<p>I have a visitors item in the video table. How can I find out the total number of visitors for each actor (stars) in the movies he/she appeared in? </p>
I used your json data, but you can process it more efficiently. I really recommend you read https://laravel.com/docs/9.x/collections this documentation about collections.