-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG] hasMany and hasOne relation not working with ObjectId #2788
Comments
I propose this solution to get around the problem without breaking the existing system. protected bool $castKey = true;
public function getIdAttribute($value = null): mixed
{
return $this->castKey ? parent::getIdAttribute($value) : $value;
}
public function accessTokens(): HasMany
{
$this->castKey = false;
$hasMany = $this->hasMany(AccessToken::class, 'userId', '_id');
$this->castKey = true;
return $hasMany;
} 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. |
I have a simple replication for this issue |
The only way I've found to stop The following patch will return a string for is_string($model->id); // true
$model->_id instanceof ObjectId; // true <?php
declare(strict_types=1);
namespace App\MongoDB\Eloquent;
use MongoDB\BSON\ObjectId;
use MongoDB\Laravel\Eloquent\Model;
/**
* Trait IdAttributePatch
* @link https://github.com/mongodb/laravel-mongodb/issues/2753
* @link https://github.com/mongodb/laravel-mongodb/issues/2788
* @mixin Model
* @property ObjectId $_id
* @property string $id
*/
trait IdAttributePatch
{
/**
* Determine if a get mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasGetMutator($key): bool
{
return $key === '_id' || parent::hasGetMutator($key);
}
/**
* Get the value of an attribute using its mutator.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function mutateAttribute($key, $value): mixed
{
if ($key === '_id') {
// replicate getIdAttribute but without the (string) casting
return $value ?: ($this->attributes['_id'] ?? $value);
}
return parent::mutateAttribute($key, $value);
}
public function getQueueableId(): string
{
return (string) parent::getKey();
}
}
` |
Hello
The _id autocast is a problem on HasOne and HasMany relations, as it prevents comparisons with ObjectId
Indeed, this relationship always returns me null
But if I remove the line
The relation working
The text was updated successfully, but these errors were encountered: