DomainFlag
DomainFlag

Reputation: 564

Ordering data from a table with the help of other table by using relationships with laravel?

I have the controller with the query:

$Comments = Comment::orderBy('id_parent', 'asc')->get();

And I have the Comment model:

class comment extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function votes()
    {
        return $this->hasMany('App\Vote', 'comment_id', 'id_comment');
    }
}

I want to retrieve the comments data sorted in a specific way, every comment has multiply votes voted by different users, so the count('vote') is the number of votes for each comment. The problem is that I am stuck with how to call the specific votes function in the model so that it can count the column vote and order it either asc or desc.

That in the end I can have the $Comments sorted also by the total number of votes.

Upvotes: 1

Views: 53

Answers (2)

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

Using sortBy:

$comments=Comment::with('votes')->get()->sortBydesc('votes');
foreach($comments as $comment)
{
   echo $comment->votes->count('vote');
}

Upvotes: 0

Amit Gupta
Amit Gupta

Reputation: 17708

You can try as:

$Comments = Comment::withCount('votes')->orderBy('votes_count', 'asc')->get();

withCount() method is used when you want to count the number of results from a relationship without actually loading them, which will place a {relation}_count column on your resulting models.

Upvotes: 1

Related Questions