"Laravel joins two tables and calculates the sum of the columns of the given related table"
P粉617597173
P粉617597173 2023-09-05 16:22:37
0
1
456
<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粉617597173
P粉617597173

reply all(1)
P粉486743671
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!