Shakti
Shakti

Reputation: 189

Laravel 5 eager loading, select column from eloquent relationship

I am trying to

1. select `DOS`,`name`,`fin`,`ins_type` from events table. 
2. site_name from sites table
3. client_name from clients table

but unable to access site_name, client_name column in select statement

->select('DOS','name','fin','ins_type')  

How to add these columns site.site_name, client.client_name in above select statement.

Eloquent query is

 $events = Event::with([
                    'site'=>function($q){
                        $q->select('site_id','site_name','client_id');
                    },
                    'site.client'=>function($q2){
                        $q2->select('client_id','client_name');
                    }])
                ->select('DOS','name','fin','ins_type')
                ->get();

Upvotes: 0

Views: 908

Answers (3)

Canaan Etai
Canaan Etai

Reputation: 3765

I myself got a little problem with these also until i discover that you need to add the foreign key to the select statement inside the "with" closure.

the column that relates "client" to "site" and "site" to "Event"

Upvotes: 0

Habib Ridho
Habib Ridho

Reputation: 13

I found a simple solution from the comment section in here. It is possible to put the column selection in the model. So in your case, your Event model could be something like this.

public function site()
{
    return $this->belongsTo('App\Site')->select('id', 'name', 'client_id');
}

Then, in your controller you simply call the function.

$events = Event::with('site')->get();

I haven't tried how this goes with the nested eager loading though.

Upvotes: 0

show-me-the-code
show-me-the-code

Reputation: 1553

How about this?

$events = Event::with([
                'site'=>function($q){
                    $q->with(['client'=>function($qq){
                        $qq->select('client_id','client_name');
                    }])->select('site_id','site_name','client_id');
                }])
            ->select('DOS','name','fin','ins_type')
            ->get();

Upvotes: 1

Related Questions