Home  >  Q&A  >  body text

"Laravel joins two tables and calculates the sum of the columns of the given related table"

<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>
P粉617597173P粉617597173380 days ago459

reply all(1)I'll reply

  • P粉486743671

    P粉4867436712023-09-06 00:14:49

    collect($stars->first()['videos'])->sum(visitors);

    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.

    reply
    0
  • Cancelreply