[BUG] hasMany and hasOne relation not working with ObjectId

Author: florianJacquesCreated Mar 21, 2024Updated Jul 15, 2025
Labelstracked-in-jira

Hello The _id autocast is a problem on HasOne and HasMany relations, as it prevents comparisons with ObjectId

php
public function getIdAttribute($value = null)
{
    // If we don't have a value for 'id', we will use the MongoDB '_id' value.
    // This allows us to work with models in a more sql-like way.
    if (! $value && array_key_exists('_id', $this->attributes)) {
        $value = $this->attributes['_id'];
    }

    // Convert ObjectID to string.
    if ($value instanceof ObjectID) {
        return (string) $value;
    }

    if ($value instanceof Binary) {
        return (string) $value->getData();
    }

    return $value;
}

Indeed, this relationship always returns me null

php
public function accessToken(): HasOne
{
    return $this->hasOne(AccessToken::class, 'userId', '_id');
}

But if I remove the line

php
// Convert ObjectID to string.
if ($value instanceof ObjectID) {
    return (string) $value;
}

The relation working