duanlei0282 2014-06-25 20:43
浏览 48

在Laravel ORM中通过投票排序

I have 3 Models... Category, Post, Vote

When viewing a category, I am showing an index of all Posts in that category. So I'm doing something like foreach ($category->posts as $post) in my view.

The question I have now is how can I order the posts based on the sum of votes they have?

I have standard relationships setup, so that a post hasMany votes.

  • 写回答

1条回答 默认 最新

  • douxian0279 2014-06-25 22:28
    关注

    You can do it either by defining a helper relation on the Post model and sorting the collection after the relation is loaded OR simply by joining the votes and ordering in the query.

    1 RELATION

    // Post model
    public function votesSum()
    {
      return $this->hasOne('Vote')->selectRaw('post_id, sum(votes) as aggregate')->groupBy('post_id');
    }
    
    // then
    $category->posts->load('votesSum'); // load relation on the collection
    
    $category->posts->sortByDesc(function ($post) {
        return $post->votesSum->aggregate;
    });
    
    // access votes sum like this:
    $category->posts->first()->votesSum->aggregate;
    

    2 JOIN

    $category->load(['posts' => function ($q) {
       $q->leftJoin('votes', 'votes.post_id', '=', 'posts.id')
           ->selectRaw('posts.*, sum(votes.votes) as votesSum')
           ->groupBy('posts.id')
           ->orderBy('votesSum', 'desc');
    }]);
    
    // then access votes sum:
    $category->posts->first()->votesSum;
    

    You can use scope for that:

    // Post model
    public function scopeOrderByVotes($query)
    {
        $query->leftJoin('comments','comments.post_id','=','posts.id')
          ->selectRaw('posts.*,sum(comments.id) as commentsSum')
          ->groupBy('posts.id')
          ->orderBy('commentsSum','desc');
    }
    
    // then
    $category = Category::with(['posts' => function ($q) {
        $q->orderByVotes();
    }])->whereSlug($slug)->firstOrFail();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题