简体   繁体   中英

No results when eager loading relationship, but relationships exists

I have 2 models using UUIDs. I've created an abstract class called Model that extends \Illuminate\Database\Eloquent\Model , and sets the following default:

public $incrementing = false;

My issue is that the lines relationship does NOT return any results when using ->with('lines'), but if I don't use ->with('lines') it DOES return results:

Example 1 (FAILS):

$lines_count = Order::whereId($id)->with('lines')->first()->lines->count(); // 0

Example 2 (WORKS):

$lines_count = Order::whereId($id)->first()->lines->count(); // 2

Example 3:

$quotation = Order::whereId($quotation_id)
    ->with('lines')
    ->withCount('lines')
    ->firstOrFail();
dd($quotation->lines_count.' - '.$quotation->lines); // Returns "2 - 0"

The relationships:

Order

class Order extends Model {
    public function lines()
    {
        return $this->hasMany(OrderLine::class, 'order_id', 'id');
    }
}

OrderLine

class OrderLine extends Model {
    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }
}

Thank you in advance. I'm really struggling.

Laravel has started, in version 6, doing some eager loading optimisations when the join fields are integers, which is the default assumption.

However if you have UUIDs which are strings you need to specify this in your model using:

public $incrementing = false;
protected $keyType = 'string';

More details in the docs

The issue was that previously, when using UUIDs, I was only setting $incrementing to false, but apparently (maybe from Laravel 7) it also made a different to specify the $keyType variable. It was set to int by default, so my UUIDs were transformed to "0".

The reason I was able to retrieve the relationships after loading the model, is because my UUID was outputted from the DB, whereas, when working with eager loading, I guess it's somewhat more strict (and only accepts values matching the $keyType).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM