0

I have the following code:

    Incident::where('id','<','35')->with('priority')->paginate(15);

Right now this returns the following: ID, title, description, priority_id and the priority object.

I would like to retrieve only ID, title and the priority object, without description nor priority_id but I want them in a specific order, like this: ID, priority and title.

But when I do the following:

    Incident::where('id','<','5')->with('priority')->paginate(15, array('id', 'priority', 'title'));

I get an error saying column incidents.priority not found.

Is there any way to select only the columns I want and in the order I want them when one of them is referenced through a FK?

Thank you!

3 Answers3

0

You don't need to include priority in the list: Incident::where('id','<','5')->with('priority')->paginate(15, array('id', 'title'));

Vitalij
  • 658
  • 8
  • 22
0

If you pass a callback to the with method you can specify the order like so:

Incident::where('id','<','35')
    ->with(['priority' => function ($query) {
        $query->select('id', 'priority', 'title');
    }])
    ->paginate(15);
tam5
  • 3,197
  • 5
  • 24
  • 45
0

Your query is not a join. The with('priority') is actually a 2nd separate query that is executed after the Incident query and then attached to the Incident models. If you want to reference columns and use a join you would do it like:

Incident::select('id', 'priorities.*', 'incidents.title')
    ->leftJoin('priorities', 'priorities.id', '=', 'incidents.priority_id')
    ->where('incidents.id', '>', '5')
    ->paginate(15);

If you don't want to use the above then @tam answer would be best but make sure with his solution to include the id in the sub query callback because that is how the relation attaches itself to the parent model after the query is ran.

Eric Tucker
  • 6,144
  • 1
  • 22
  • 36