0

is there a way to select only certain columns when doing eager-loading in laravel?

$columns = ['col_1', 'col_2', 'col_3'];
$model = MyModel::findOrFail(Input::get('id'), $columns);
$model->load('position');

In My model I Have defined:

public function position() {
    return $this->belongsToMany('Position', 'mymodel_positions')->withTimestamps();
}

When I don't provide the $columns parameter like MyModel::findOrFail(id). Positions are loaded correctly. However if I do provide $columns, the positions ale always empty.

What I want: eagerly load a relation AND specify the columns (Not the ones in the loaded relation). I'm sure It's possible, but i simply don't get it...

Hope for your help.

shock_gone_wild
  • 6,700
  • 4
  • 28
  • 52
  • possible duplicate of [Laravel Eager Loading - Load only specific columns](http://stackoverflow.com/questions/16994253/laravel-eager-loading-load-only-specific-columns) – Brian Dillingham Sep 07 '14 at 06:55
  • I don't think so. The question in your link is about specifying columns in the eagerly loaded model. My problem is different I think. I've already seen that question you are referring to. My Problem is about specifying columns and additionally load a model. – shock_gone_wild Sep 07 '14 at 07:12
  • Why wouldn't you want to format the model how you need it? – Brian Dillingham Sep 07 '14 at 07:17

1 Answers1

2

tldr; You always need to SELECT primary key and corresponding foreign key of the relation.

Most likely this:

$columns = ['col_1', 'col_2', 'col_3'];

doesn't contain your model's primary key, so Eloquent is unable to match related models.

That being said, all you need is:

$columns = ['id', 'col_1', 'col_2', 'col_3'];

or whatever field is the primary key.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157