【问题标题】:Performing a sum() on a collection in Laravel在 Laravel 中对集合执行 sum()
【发布时间】:2014-07-29 01:43:09
【问题描述】:

我有一个带有基本论坛系统的应用程序,用户可以多次“喜欢”一个主题。我的模型扩展了 Eloquent,我试图获得用户对特定主题的投票总和......基本上,我试图完成类似的事情:

$votes = Auth::user()
    ->votes->has('topic_id', '=', $topic->id)
    ->sum('votes');

但是,执行此操作时,我收到以下错误...

在非对象上调用成员函数 sum()

我也试过

public function show($forumSlug, $topicSlug)
{
    $topic = Topic::whereSlug($topicSlug)->first();

    $votes = Topic::whereHas('votes', function ($q) use ($topic)
    {
        $q->where('topic_id', '=', $topic->id)->sum('votes');
    });

    dd($votes);
}

但是,我收到一条错误消息:

“where 子句”中的未知列“ideas.id”(SQL:select sum(votes) 作为来自votes 的聚合,其中votes.idea_id = ideas.ididea_id = 1)`

【问题讨论】:

    标签: php laravel aggregate-functions eloquent relationship


    【解决方案1】:

    你可以尝试这样的事情(不确定你们的关系,但试试看):

    $topic = User::with(array('topics' => function ($query) use ($topic_id) {
        // $query = Topic, so it's: Topic::with('votes')
        $query->with('votes')->where('topics.id', $topic_id);
    }))->find(Auth::user()->id)->topics->first();
    
    // Count of total votes
    dd($topic->votes->count());
    

    P/S:如果不起作用,请发布您的模型的关系方法。

    【讨论】:

      【解决方案2】:

      我设法让它工作,但我不确定我是否喜欢这种方法。我很想知道是否有人知道这样做的更好方法...

      基本上,我使用我的关系来过滤()投票,然后在过滤后的集合上使用 sum()。

      public function show($forumSlug, $topicSlug)
      {
          $userId = is_null(Auth::user()) ? false : Auth::user()->id;
          $topic = Topic::whereSlug($topicSlug)->first();
      
          $votes = $topic->votes->filter(function ($votes) use ($userId)
          {
              return $votes->user_id == $userId;
          })->sum('votes');
      
          return View::make('forums.topics.show', compact('topic', 'votes'));
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-30
        • 2017-11-10
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 2021-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多