0

In Laravel 4/5 how can order a table results based in a field that are connected to this table by a relationship?

My case:

I have the users that only store the e-mail and password fields. But I have an another table called details that store the name, birthday, etc...

How can I get the users table results ordering by the details.name?

P.S.: Since users is a central table that have many others relations and have many items, I can't just make a inverse search like Details::...

insign
  • 5,353
  • 1
  • 38
  • 35

1 Answers1

2

I would recommend using join. (Models should be named in the singular form; User; Detail)

$users = User::join('details', 'users.id', '=', 'details.user_id')  //'details' and 'users' is the table name; not the model name
    ->orderBy('details.name', 'asc')
    ->get();

If you use this query many times, you could save it in a scope in the Model.

class User extends \Eloquent {
    public function scopeUserDetails($query) {
        return $query->join('details', 'users.id', '=', 'details.user_id')
    }
}

Then call the query from your controller.

$users = User::userDetails()->orderBy('details.name', 'asc')->get();
Robbie
  • 642
  • 1
  • 6
  • 12
  • Thanks for the answer but I already using this way, and it is very bad since can make conflicts when ordering columns with same name like id, etc. I was searching a more "ORM" way.. – insign Nov 26 '14 at 02:17