Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Behavior of hasManyThrough different lazy vs. eager load #14743

Closed
epicwally opened this issue Aug 10, 2016 · 1 comment
Closed

Behavior of hasManyThrough different lazy vs. eager load #14743

epicwally opened this issue Aug 10, 2016 · 1 comment

Comments

@epicwally
Copy link

epicwally commented Aug 10, 2016

As a forward, I'm working with a database that was designed very poorly (namely the references between tables are not done off PKs in many cases.) As such I have to override column names in most relations, but this hasn't been a problem. The basic structure is:

Creditor

  • _rowid (PK)
  • id

Debitor

  • _rowid (PK)
  • creditor_id (references Creditor.id)

invoices (just refactored this, hence moving towards using PKs, and more appropriate naming standards)

  • id (PK)
  • debtor_id (references Debitor._rowid)

My relationship from Creditor to Invoice is:
return $this->hasManyThrough(Invoice::class, Debtor::class, 'creditor_id', 'debtor_id', 'id');

If I lazy load by doing:
$creditor = Creditor::find($id); $creditor->invoices
Everything works fine.

If I try it with eager loading:
$creditor = Creditor::with('invoices')->find($id);
The invoices relationship on the creditor is empty.

Similarly, calling:
$creditor->load('invoices')
does not work.

In investigating the SQL generated, it seems that in the eager-loading situation, the PK of the Creditor table is being used, instead of the 'id' column that I specified.

@epicwally
Copy link
Author

I managed to come up with a fix. I modified two lines in HasManyThrough.php as follows:

Line 139:
$this->query->whereIn($table.'.'.$this->firstKey, $this->getKeys($models, $this->localKey));

Line 174:
$key = isset($this->localKey) ? $model->{$this->localKey} : $model->getKey();

This has seemed to work for my application, though I believe this is the only place I am presently using hasManyThrough, so not positive there isn't a case where this could break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant