pop icon indicating copy to clipboard operation
pop copied to clipboard

EagerPreload failing to load association

Open reggieriser opened this issue 5 years ago • 0 comments

Description

I ran into a case where EagerPreload fails to pull in an association that works fine with Eager.

Here's an example set of models that will demonstrate the problem (the referenced Address model is from pop_test.go):

type Employee struct {
	ID        int     `db:"id"`
	Name      string  `db:"name"`
	AddressID int     `db:"address_id"`
	Address   Address `belongs_to:"address"`
}

 type Move struct {
	ID           int      `db:"id"`
	EmployeeID   int      `db:"employee_id"`
	Employee     Employee `belongs_to:"employee"`
	NewAddressID int      `db:"new_address_id"`
	NewAddress   Address  `belongs_to:"address"`
}

And here's an example query using those models:

movesPreload := []Move{}
tx.EagerPreload("NewAddress", "Employee.Address").All(&movesPreload)

The NewAddress field will fail to be populated using EagerPreload, but populates fine with Eager. Tracing through the preload code, it appears to be trying to find the foreign key named address_id for the NewAddress association despite the fact it should probably first look for new_address_id. It then appears to then be walking down into the Employee struct and matching the address_id field, leading to the issue.

Note that if I add a fk_id:"new_address_id" struct tag to NewAddress, it works fine. But that's not required for Eager, and I would expect Pop to default the fk_id to new_address_id given the name of the struct field.

Steps to Reproduce the Problem

I made a test case that demonstrates the issue in a branch on my fork: https://github.com/gobuffalo/pop/compare/master...reggieriser:preload-nested-test

Expected Behavior

I would expect identical Eager and EagerPreload calls to be interchangeable with no difference in the resulting structs' values.

Actual Behavior

An association is not being loaded with EagerPreload

Info

Mac OS 10.15.7, Pop 5.3.1, not using Pop through Buffalo

reggieriser avatar Oct 23 '20 16:10 reggieriser