I'm trying to implement a sort function, using eloquent, in Laravel 4 on a Projects table using the Name field on one of a number of related table.

Tables:

Project (uses client_id, contact_id, phase_id)

Client (id, name)

Contact (id, name)

Phase (id, name)

Project holds the ID of the other 3 related tables but displays the Name field for each to make it human readable. I'm using eager loading and getting the data using:

$projects = Project::with('client', 'contact', 'phase')->get();

What I'd like to be able to do is something like:

$projects = Project::with(array('client' => function($query)
                    {
                      $query->orderBy('name', $direction);
                    }), 'contact', 'phase')->get(); 

Where the direction is determined by a query string to allow a user to switch the sort directions, on the client name in this instance. However, it doesn't work.

I'm new to Laravel and trying to get my head around the do's and don's of eloquent so any help would be appreciated.

有帮助吗?

解决方案

use joins instead of eager loading here (if I get you right, you have 1 contact,client and phase per each project), or you will need to apply sort on the collection. The latter will be cumbersome.

  Project::join('clients', 'clients.id', '=', 'projects.client_id')
     ->join('contacts', 'contacts.id', '=', 'projects.contact_id')
     ->join('phases', 'phases.id', '=', 'projects.phase_id')
     ->select(array('projects.*','clients.name as clientName','contacts.name as contactName','phases.name as phaseName'))
     ->orderBy("$orderBy", "$direction"); // $orderBy = eg. 'clientName'
     // and if you still need to load related models then uncomment:
     // with(array('contact','client','phase'))
     ->get();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top