简体   繁体   中英

Get the sum of 'value' in the votes table of all posts related to the user

I'm trying to get the link karma (like reddit does) of a user and display it on his profile page.

user: id, name, email, password..

posts: id, user_id, title, link, text...

votes: id, user_id, post_id...

I need to be able to get the sum of "value" field in "votes" table of all the posts submitted by the user

This is what I'm using now and a quick dd($user) will retrieve all the post and votes by the user. But using {{ $post->votes->sum('value') }} on the view will retrieve the sum of each post separately and not all of them together. How can I do that?

public function show($user)
    {
        $user = User::whereName($user)->with('posts.votes')->first();
        return view('user/profile')->with('user', $user);
    }

Note that dd($user) does retrieve all the posts and their votes of the user.

The View (which displays as many times as there as posts related to the user which is not what should be happening)

@foreach($user->posts as $post)
   Link Karma: {{ $post->votes->sum('value') }}
@endforeach

users: id, name, email, password..

posts: id, user_id, title, link, text...

votes: id, post_id, value, ...

In App\\User Model:

public function posts(){
    return $this->hasMany('App\Post');
}
public function votes(){
    return $this->hasManyThrough('App\Vote','App\Post');
}

In App\\Post Model:

public function votes(){
    return $this->hasMany('App\Vote');
}

Then use: App\\User::find($user_id)->post()->find($post_id)->votes()->sum('value') for sum of votes by user $user_id on post $post_id . App\\Post::find($post_id)->votes()->sum('value') for sum of all votes on post $post_id . App\\User::find($user_id)->votes()->sum('value') for sum of all votes by user $user_id .

You can use foreach() to loop through any of the combinations.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM