Giacomo Sarrocco
Giacomo Sarrocco

Reputation: 441

Eloquent order by one-to-one-related column

Good morning everyone! I'm using Laravel 5.0 and Eloquent to build a displaying page for results of some replies on the database. Replies are in reservations table, which "belongs" to users table since every reservation is linked to a person.

class Reservation extends Model {

    public function user()
        {
            return $this->belongsTo('App\User');
        }
}

I would like to display results, the reservations, ordered by the last name column of the user. So like:

$reservations = Reservation::orderBy( /*users.last_name*/ )->get();

But I dont'know how. Thank you in advance for your time.

Upvotes: 3

Views: 247

Answers (1)

PiranhaGeorge
PiranhaGeorge

Reputation: 999

You'll need to join the tables to order by a foreign column.

$reservations = Reservation::join('users', 'users.id', '=', 'users.reservation_id')
->orderBy('users.last_name', 'asc')->get();

Upvotes: 1

Related Questions