Morgan
Morgan

Reputation: 196

Querying ORM with WHERE clause - Eloquent/Laravel 4

The relevant code is at: https://gist.github.com/morganhein/9254678

I have nested resource controllers, which query similarly structured tables in a database.

If I go to www.example.com/v1/jobs/1/departments, I want to query all departments that are associated with job 1. However I cannot figure out how to do that using the ORM.

Help?

Upvotes: 0

Views: 253

Answers (1)

user2920996
user2920996

Reputation:

I didn't test, but I would suggest you to try something like this:

Route::resource('/v1/jobs/{id}/departments', 'DepartmentController');    
Route::resource('/v1/jobs', 'JobController');

After that, your DepartmentController methods will receive one argument, which is job id in your case. It is easier to use find() method if you are using id to retrieve any specific model. When you found the model you can get access to related models.

class DepartmentsController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index($jobId)
    {
        Clockwork::startEvent('List_Default_Departments', 'Starting.');
        $positions = Auth::user()->jobs()->find($jobId)->departments;
        Clockwork::endEvent('List_Default_Departments', 'Done.');
        return Response::json($positions->toArray());
    }
}

Note: There is a different between $job->departments() (returns Builder object to create more complex queries) and $job->departments (returns Collection object directly).

Also if you would like to get the list of jobs with all related departments you can always call:

$jobs = Auth::user()->jobs()->with('departments')->get();

Upvotes: 1

Related Questions