Open
Description
Hello
The _id autocast is a problem on HasOne and HasMany relations, as it prevents comparisons with ObjectId
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
public function accessToken(): HasOne
{
return $this->hasOne(AccessToken::class, 'userId', '_id');
}
But if I remove the line
// Convert ObjectID to string.
if ($value instanceof ObjectID) {
return (string) $value;
}
The relation working
Activity
florianJacques commentedon Mar 21, 2024
I propose this solution to get around the problem without breaking the existing system.
What do you think?
Unfortunately does not work with method....
I don't know why you put a default attribute mutator on the id, I wonder if it shouldn't be removed.
masterbater commentedon Mar 23, 2024
#2753 (comment)
I have a simple replication for this issue
tarranjones commentedon Jan 17, 2025
The only way I've found to stop
_id
from auto casting is to capture it beforemutateAttribute
strips the leading underscore.By the time
getIdAttribute
is called we do not know which property was calledid
or_id
.The following patch will return a string for
$mode->id
and a ObjectID for$model->_id
.This fixes the
hasOne
hasMany
issues without needing to specify additional parameters.yurik94 commentedon Jul 15, 2025
any news?
alcaeus commentedon Jul 15, 2025
No, we haven't tackled this one yet. We are tracking this internally in PHPORM-291, so if you have a JIRA account you may follow that for updates as well. We'll also be updating this issue here when the situation changes.