Laravel count function in the model, then sortBy count ()

I am trying to sort the table Postsby the number of votes a received Post. Votes are stored in another table.

(Votes: post_id, user_id, vote_type)

Post Model:

class Post extends Model
{
    public function user()
    {
      return $this->hasOne(User::class);
    }

    public function votes()
    {
      return DB::table('votes')->where('post_id','=',$this->id)->sum('vote_type');
    }
}

The vote functions return the number of votes received by mail (Voices a stored in a separate table)

Now I'm trying to order everything Postsby the number of votes they received.

Post::get()->sortBy('votes');

This returns a follwing error:

The communication method should return an object of type Illuminate \ Database \ Eloquent \ Relations \ Relation

I would be grateful for any help to fix this!

+4
source share
3 answers

try

Post::get()->sortBy(function($query){
return $query->votes();
});

Alternative

withCount(), {relation}_count .

Post::withCount(['votes'])
->orderBy('votes_count')
->get()

docs

Post::withCount(['votes'])
->orderBy('votes_count')
->paginate();
+4

Post Model

 protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('voteCount', function ($builder) {
            $builder->withCount('votes');
        });
    }

voteCount, .

:

Post::get()->sortBy('voteCount');

, voteCount PostModel, , , .

0

, , getVotesAttribute() Post.

class Post extends Model
{
    public function user()
    {
      return $this->hasOne(User::class);
    }

    public function getVotesAttribute()
    {
      return DB::table('votes')->where('post_id','=',$this->id)->sum('vote_type');
    }
}
-1

Source: https://habr.com/ru/post/1687301/


All Articles