2013-08-09 15 views
61

Sono in loop su tutti i commenti postati dall'autore di un particolare post.Laravel orderBy su una relazione

foreach($post->user->comments as $comment) 
    { 
     echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>"; 
    } 

Questo mi dà

I love this post (3) 
This is a comment (5) 
This is the second Comment (3) 

Come vorrei ordinare dal post_id modo che l'elenco di cui sopra è ordinato come 3,3,5

risposta

136

E 'possibile estendere la relazione con interrogazione funzioni:

<?php 
public function comments() 
{ 
    return $this->hasMany('Comment')->orderBy('column'); 
} 

[modifica dopo il commento]

<?php 
class User 
{ 
    public function comments() 
    { 
     return $this->hasMany('Comment'); 
    } 
} 

class Controller 
{ 
    public function index() 
    { 
     $column = Input::get('orderBy', 'defaultColumn'); 
     $comments = User::find(1)->comments()->orderBy($column)->get(); 

     // use $comments in the template 
    } 
} 

modello utente predefinito + semplice esempio di controller; quando ottieni l'elenco dei commenti, applica semplicemente orderBy() basato su Input :: get(). (assicuratevi di fare un controllo di input;))

+2

Qualcuno ha già suggerito questo nel Forum di Laravel, ma voglio essere in grado di farlo nel Controller in modo da poter scegliere quale campo ordinare in base all'input dell'utente . Forse dovrei averlo reso più chiaro nella domanda. – PrestonDocks

+0

Ho aggiunto un secondo esempio –

+1

Grazie Rob, mi hai messo sulla strada giusta. La risposta effettiva era $ comments = User :: find (10) -> comments() -> orderBy ('post_id') -> get(); Sembrava che avesse bisogno del metodo get() per funzionare. Se puoi aggiungere get() alla tua risposta, la contrassegnerò come risposta accettata. – PrestonDocks

Problemi correlati