How to select columns from joined tables: laravel eloquent

Viewed 21750

I have a different problem from this. The scenario is same but I am in need of more filtration of the results.

Let me explain.

Consider I have 2 tables

vehicles

 id
 name
 staff_id
 distance
 mileage

staffs

 id
 name
 designation

I want to select only id and name from both tables(Models). The Vehicle Model contain a belongsTo relation to Staff model.

class Vehicle extends Model
{
    public function staff()
    {
      return $this->belongsTo('App\Staff','staff_id');
    }
}

and I joined using this

Vehicle::where('id',1)
            ->with(['staff'=> function($query){
                            // selecting fields from staff table
                            $query->select(['staff.id','staff.name']);
                          }])
            ->get();

When I put fields in ->get() like this

->get(['id','name'])

it filters the vehicle table but produce no result of Staff table.

Any ideas?

3 Answers

The shortest and more convenient way I guess would be :

Vehicle::select('id','name','staff_id')->where('id',1)
->with('staff:id,name' )->get();

foreign key should present for selection .

Since Laravel 5.7 you can use with() like this :

with('staff:id,name' )

for granular selection.

Related