booni3's avatar

L6 Upgrade - Eager Loading Issue with UUID's as ID

I have just upgraded to L6 from 5.8.

Eager loading is failing to work on some rows with a basic BelongsTo relationship. If I bypass eager then it works every time, but with it, I get failures (null returned) but only on some records. If I query the same relationship/row without eager it then works.

// With Eager loading
$orders = Order::query()->with(['orderAddress'])->get();

foreach($orders as $order){
    dump($order->orderAddress->first_name); // Fails, but only on some rows
    dump($order->orderAddress()->first()->first_name); // works every time
}

// Without Eager loading
$orders = Order::all();

foreach($orders as $order){
    dump($order->orderAddress->first_name); // works every time
}

Relationship

public function orderAddress() : BelongsTo
{
    return $this->belongsTo(OrderAddress::class);
}

When inspecting the eager loading query, it shows the issue:

select * from `order_addresses` where `order_addresses`.`id` in (1, 2, 0, 0, 0, 0, 11189, 0, 122, 140, 199, 1, 1, 1, 100000, 10000, 1, 262, 294409 
...

The ID's are stored as CHAR 32 UUID's but Eloquent is trying to convert them to integers. Any ideas why?

  • I have incrementing = false; already
0 likes
1 reply
booni3's avatar
booni3
OP
Best Answer
Level 3

Ok, turns out after Laravel 5.7 you need to specify the key type as a string. So setting the keyType in my UUID Trait fixed it.

trait UuidForKey
{
    public function initializeUuidForKeyTrait()
    {
        $this->keyType = 'string';
    }

    /**
     * Boot the Uuid trait for the model.
     *
     * @return void
     */
    public static function bootUuidForKey()
    {
        static::creating(function ($model) {
            $model->incrementing = false;
            $model->{$model->getKeyName()} = (string) Str::uuid();
        });
    }
...

https://github.com/laravel/framework/issues/26582

1 like

Please or to participate in this conversation.