1

I have custom code where I must get specific columns from relation data:

$jobs = Job::with('user:id, name')
           ->where('type', 0)
           ->where('status', 1)
           ->orderBy('updated_at', 'DESC')
           ->get();

When I run this code Laravel return me error message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ' name' in 'field list'

How can I solve this error?

Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125

2 Answers2

4

In this code has space with('user:id, name'). Problem is space.
Try this one

$jobs = Job::with('user:id,name')
    ->where('type', 0)
    ->where('status', 1)
    ->orderBy('updated_at', 'DESC')
    ->get();
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55
4

It can be done one by passing a closure function in with() as second index of array like

$jobs = Job::with(['user' =>  function($q){
                $q->select('id','name');
            }])->where('type', 0)
               ->where('status', 1)
               ->orderBy('updated_at', 'DESC')
               ->get();