0

I started using the eager loader in Laravel 4.

I have two tables (campaigns and reports) whit following relation in the Campaigns Model:

public function reports() {
   return $this->hasMany('Reports', 'account_id', 'adwords_id')->select('CLICKS', 'COST');
}

I had to use non-conventional column names here unfortunaly.

When I now do:

$data['campaigns'] = Campaign::get();
foreach ($data['campaigns'] as $campaign) {
  print_r($campaign->reports);
}

it outputs all the reports for the campaigns the way it should.

But now I want to eager load this:

$data['campaigns'] = Campaign::with('reports')->get();
foreach ($data['campaigns'] as $campaign) {
   print_r($campaign->reports);
}

This outputs me just empty arrays.

What am I doing wrong? I really want to use eager to have fasters scripts...

3
  • 1
    Duplicate, read this: Getting specific columns with eager loading laravel 4 Commented Oct 14, 2014 at 13:35
  • Thanks, this solved my problem. I had to select the keys. Strange that it worked when not using Eager Loader even without having the key selected. Commented Oct 14, 2014 at 13:44
  • Not that strange. If you tried to load that relation on a collection then it wouldn't work as well, however when you do it on a single parent, then there is no need for matching parents - children, so basically whatever comes from the query is set as a relation on the parent model. Commented Oct 14, 2014 at 14:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.