2017-06-15 5 views
0

So habe ich einen Abschnitt Menschen können Kommentare machen und geben Sie gerne zu diesen Kommentaren. Ich möchte die Kommentare basierend darauf organisieren, wie viele Likes es hat.Abfrage nach Beziehung Anzahl Laravel 4.2

so verwende ich so etwas wie dieses

$art = Article::with('category') 
->with(array('comments' => function($comments){ 
    //i get the comments related to the article and the count of likes it has 
    $comments->with('likesCount'); 
})) 
->find($id); 

dies ist das Modell

<?php 

class Comment extends Eloquent { 
    public function likes() 
    { 
     return $this->hasMany('CommentsLike','comment_id'); 
    } 
    //here i take the count of likes, if i use ->count() it throw 
    public function likesCount() 
    { 
     return $this->likes() 
     ->groupBy('comment_id') 
     ->selectRaw('comment_id,count(*) as comment_likes'); 
    } 
} 

wie kann ich mein Kommentar sortieren basierend auf, was ich in likesCount bekam

Antwort

0

Verwenden orderBy() bis likesCount() Funktion.

public function likesCount() 
{ 
    return $this->likes() 
    ->groupBy('comment_id') 
    ->selectRaw('comment_id,count(*) as comment_likes') 
    ->orderBy('comment_likes', 'desc'); 
}