Uploaded image for project: 'PHP ORMs'
  1. PHP ORMs
  2. PHPORM-291

laravel-mongodb - Issue #2788: [BUG] hasMany and hasOne relation not working with ObjectId

    • Type: Icon: Question Question
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: Laravel
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      florianJacques has created Issue #2788: [BUG] hasMany and hasOne relation not working with ObjectId in laravel-mongodb. This Jira ticket was filed by GromNaN

      Issue Text:
      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

            Assignee:
            Unassigned Unassigned
            Reporter:
            dbeng-pm-bot TPM Jira Automations Bot
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              None
              None
              None
              None