topclaudy / compoships

Multi-columns relationships for Laravel's Eloquent ORM
MIT License
1.12k stars 130 forks source link

BUG: Error on eager loading/matching for BelongsTo #115

Closed ragingdave closed 3 years ago

ragingdave commented 3 years ago

This might extend past just BelongsTo, but in using this package and attempting to eager load a relation using a non-primary key (don't think that has anything to do with it, but.....), the loaded relations aren't the correct ones, and matching then fails improperly.

As an Example,

App\Product extends Model
{
    use Compoships;
    // standard auto-increment primary
    // secondary cols of manu and sku

    ...
    public function oldProduct()
    {
        return $this->belongsTo(OldProduct::class, ['manu', 'sku'], ['manu_old', 'sku_old']);
    }

App\OldProduct extends Model
{
     use Compoships;
     //standard auto-increment primary
    // secondary cols of manu_old and sku_old
}

Using this configuration specifically in tandem with a dataset like:

App\Product
id(int), manu(string), sku (string)
1, TEST, 1234
2, TEST, 01234
3, TEST, 001234

The BelongsTo logic found here https://github.com/topclaudy/compoships/blob/master/src/Database/Eloquent/Relations/BelongsTo.php#L156

Will try and run an array_unique on a multi-dimensional array which, isn't documented to what will happen, but will end up converting an array like the definition above would generate in that defined relation (oldProduct) on the App\Product of

[
  [
    "TEST",
    "1234"
  ], [
    "TEST",
    "01234"
  ], [
    "TEST",
    "001234"
  ]
];

// when run through array_unique becomes:

[
     [
       "TEST",
       "1234",
     ],
]

This essentially can cause any logic depending on eager loading in this scenario to be entirely broken and break applications due to eager loading not creating the right query to load the right models, which are then not matched properly in large datasets.