Wednesday, March 15, 2017

laravel select specific columns but with relationships

I'm currently optimizing my application and one thing is selecting only the things from database which are really needed.

For example when I'm retrieving a User object I normally do it like this:

$user = User::where($attribute, '=', $value)->first();

This code will give me back a full user object with all the columns. My users table is pretty big, so I thought it is a good idea to only select the columns which I need like this:

$user = User::where($attribute, '=', $value)->first($columns);

This is also working as expected. But my problem is, as soon as I specify columns, the relationships of the $user variable are not working anymore, because it is no longer an object.

My question: Is it possible to select only a few columns but still be able to use relations like

$user->parents

Thanks!



via Phil

Advertisement