【问题标题】:Get the sum of 'value' in the votes table of all posts related to the user获取与用户相关的所有帖子的投票表中“价值”的总和
【发布时间】:2015-12-23 21:52:15
【问题描述】:

我正在尝试获取用户的链接业力(就像 reddit 一样)并将其显示在他的个人资料页面上。

用户:ID、姓名、电子邮件、密码..

帖子:id、user_id、标题、链接、文本...

投票:id、user_id、post_id...

我需要能够获取用户提交的所有帖子的“投票”表中“价值”字段的总和

这是我现在使用的,一个快速的dd($user) 将检索用户的所有帖子和投票。但是在视图上使用{{ $post->votes->sum('value') }} 将分别检索每个帖子的总和,而不是全部一起检索。我该怎么做?

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

请注意,dd($user) 会检索用户的所有帖子及其投票。

视图(与用户相关的帖子显示的次数与不应该发生的情况一样多)

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

【问题讨论】:

  • 你在 $user->votes 上尝试过 haveManyThrough() 吗?
  • 不,我没有。我还没有遇到过这种方法。
  • 查看文档。这很容易。我认为它会工作;)
  • @Mithredate $user->votes 会给我用户的投票,我想要每个人在他(用户)帖子上的投票。
  • 那么我认为你缺少括号。

标签: php laravel laravel-5 eloquent eager-loading


【解决方案1】:

用户:ID、姓名、电子邮件、密码..

帖子:id、user_id、标题、链接、文本...

投票:id、post_id、值、...

App\User 模特:

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

App\Post 模特:

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

然后使用: App\User::find($user_id)->post()->find($post_id)->votes()->sum('value') 用户$user_id 在帖子$post_id 上的投票总和。 App\Post::find($post_id)->votes()->sum('value') 用于帖子 $post_id 上所有投票的总和。 App\User::find($user_id)->votes()->sum('value') 代表用户$user_id 的所有投票总和。

您可以使用foreach() 循环访问任何组合。

【讨论】:

  • 谢谢伙计。显然是的,我错过了一个括号,但是使用你的新 sn-p 我能够创建一个新变量 $linkKarma 并将其传递给视图,无需 foreach
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2019-03-31
  • 1970-01-01
相关资源
最近更新 更多