laravel/framework — pull request #3129 by rnavarro (2014-01-04 23:16:52+00:00)
Title: Fix HasManyThrough dictionary foreign key bug

I'm seeing an issue with incorrect foreign keys being assigned when using the HasManyThrough relation.

Here is my model relation:

```php
class EloquentContactRepository extends Eloquent {
protected $table = 'company';

public function invoices()
{
return $this->hasManyThrough(
'Project\Invoice\EloquentInvoiceRepository',
'Project\SalesOrder\EloquentSalesOrderRepository',
'company_id',
'order_id'
);
}
}
```

Here is my table structure:

Company
```id, name```

SalesOrder
```id, company_id```

Invoice
```id, order_id```

The issue I'm seeing is that the $foreign variable is being set to "eloquent_contact_repository_id" when it should really be set to "company_id"

This doesn't appear to be an issue when accessing dynamic attributes directly, it's only an issue when eagerly fetching relation data using the "with" parameter.

I propose we change the code to this:

```php
protected function buildDictionary(Collection $results)
{
$dictionary = array();

$foreign = $this->firstKey;

// First we will create a dictionary of models keyed by the foreign key of the
// relationship as this will allow us to quickly access all of the related
// models without having to do nested looping which will be quite slow.
foreach ($results as $result)
{
$dictionary[$result->{$foreign}][] = $result;
}

return $dictionary;
}
```

I ran the default test suite and it didn't appear to break anything. Similarly, it didn't change any functionality in my testing when using eagerly fetched relations or dynamic attribute fetching.

Thoughts?