6

How can I sort my result with related tables?

I have this tables: Clients and Managers (users table)

Client.php

<?php

class Client extends Eloquent {
    protected $table = 'clients';

    public function Manager(){
        return $this->belongsTo('User','manager','id');
    }
    public function Transaction(){
        return $this->hasMany('ClientTransaction','client','id');
    }
}

Users.php (default Laravel's model)

My question is how can I query table clients to be sorted by Manager's name.

Here is my code so far:

public function getClients() {
    // Sorting preparations
    $allowed    = array('name','contact','money');
    $sort       = in_array(Input::get('sort'), $allowed) ? Input::get('sort') : 'name';
    $order      = Input::get('order') === 'desc' ? 'desc' : 'asc';
    // Get Clients from DB
    if($sort == 'contact'){
        $clients    = Client::with(array('Manager' => function($query) use ($order) {
            $query->orderBy('name', $order);
        }));
    } else {
        $clients    = Client::orderBy($sort, $order)->with('Manager');
    }
    // Filters
    $cname      = null;
    if(Input::has('cname')){
        $clients    = $clients->where('name', Input::get('cname'));
        $cname      = '$cname='.Input::get('cname');
    }
    // Pagination
    $clients    = $clients->paginate(25);
    // Return View
    return View::make('pages.platform.clients')
        ->with('clients', $clients);
}

If I try to sort by Name it sorts OK by Clients name but if I try to sort by contact it needs to sort by User's (Manager's) name.

Qrazier
  • 162
  • 4
  • 15
  • Read http://stackoverflow.com/questions/14299945/how-to-sort-by-a-field-of-the-pivot-table-of-a-many-to-many-relationship-in-eloq – Luis Masuelli Aug 04 '14 at 16:52

1 Answers1

13

Try this.

$clients = Client::join('users as manager', 'manager.id','=','clients.manager')
            ->orderBy('manager.name', $order)
            ->select('clients.*') // avoid fetching anything from joined table
            ->with('Manager');  // if you need managers data anyway

Put this into your if statement if($sort == 'contact'){ /***/ }

Milos Miskone Sretin
  • 1,748
  • 2
  • 25
  • 46