1
votes

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?

2
do you have name field in the users table ?Sagar Gautam
Here is my $fillable variable values: protected $fillable = ['name', 'email', 'password', 'phone', 'status'];Andreas Hunter
Unknown column ' name', there is blank space ' name'Niklesh Raut
@AndreasHunter Space is a Problem here so remove space only.Jignesh Joisar

2 Answers

4
votes

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();
3
votes

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();