How to Order Related Model Data?

2

I have the following relationship in my application:

Template Customer :

class Cliente extends Model
{
    protected $table = 'clientes';

    public function Usuario(){ 
        return $this->hasMany('App\Models\Admin\Usuario', 'id_cliente');
    }    
}

Template User :

class Usuario extends Model
{
    protected $table = 'usuarios';

    public function Cliente(){ 
        return $this->belongsTo('App\Models\Admin\Cliente', 'id_cliente'); 
    }
}

But I need to sort the results when I call all the client users in my view:

@foreach($Cliente->Usuario as $usuario)...

This is just an example, I have several relationships in my application that I need to apply this sort filter, how can I do this?

    
asked by anonymous 18.04.2016 / 15:54

1 answer

4

In Laravel it is possible to preload the results of the relationships of a given model. So along with this upload, you can also add conditions that will be applied to the relationships that will be uploaded along with your query. This is done through the with method (Whenever you want to use it, it must be the first method to be called).

In the controller, you can do this:

$with['usuarios'] = function ($query) {
    return $query->orderBy('nome');
};

$cliente = Cliente::with($with)->find($id);

Or you can also separate the two, and make a second query for users based on the client query.

 $cliente = Cliente::find($id);

 $usuarios = $cliente->usuarios()->orderBy('nome')->get();

In the second example, you would have to foreach in $usuarios .

Sorting the collection

You can also sort the relationship data after the query completes.

For example, I want to sort my users who are related to a client by name. And then I want to list them again and sort them by update date.

Instead of doing two queries, you can do this:

#controller

 $cliente = Cliente::with('usuarios')->find($id);

 $ordenadores['nome'] = function ($usuario)
 {
      return $usuario->nome;
 };

 $ordenadores['atualizacao'] = function ($usuario)
 {
        return $usuario->created_at;
 };

 return view('minha_view', compact('cliente', 'ordenadores'));

Then in the view, you can do this:

#view

@foreach($cliente->usuarios->sortBy($ordenadores['nome']) as $usuario)

@endforeach


@foreach($client->usuarios->sortBy($ordenadores['atualizacao']) as $usuario)

@endforeach

Note : In some cases, it is not necessary to use Callback in sortBy . Just pass the field name as the argument of sortBy , to sort the data in the Collection.

@foreach($client->usuarios->sortBy('created_at') as $usuario)

@endforeach

Tip

Generally, to maintain readability of your model's methods, I suggest you use singular for one-to-one relationships like belongsTo and hasOne , and plural for hasMany or belongsToMany and related ).

    
18.04.2016 / 16:36