Eager loading MorphTo relationships ignores withTrashed() and other query macros

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Unresolved
    • Priority: Major - P3
    • None
    • Affects Version/s: None
    • None
    • 5
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      Reported in https://github.com/mongodb/laravel-mongodb/issues/3454 (duplicate of the older https://github.com/mongodb/laravel-mongodb/issues/1361).

      Eager loading a morphTo() relationship with withTrashed() does not return soft-deleted models. Lazy loading works, only eager loading is affected.

      class Photo extends Model
      {
          public function hasImage(): MorphTo
          {
              return $this->morphTo()->withTrashed();
          }
      }
      
      Photo::with('hasImage')->get(); // hasImage is null when the related model is soft-deleted
      

      Cause

      MongoDB\Laravel\Relations\MorphTo::getResultsByType() is a stripped-down copy of the Laravel implementation, unchanged since 2015. It builds the query with a plain $instance->newQuery() and drops everything the parent class does:

      • replayMacros(), which is how withTrashed(), withoutTrashed(), onlyTrashed() and buffered select() calls reach the related model query. MorphTo cannot apply those methods on the parent query because the macros only exist on the related model, so it buffers them and replays them per morph type.
      • mergeConstraintsFrom()
      • with() / withCount(), which makes morphWith() and morphWithCount() no-ops
      • the per-type callback registered by constrain()

      The two reasons the override existed no longer apply: DocumentModel::qualifyColumn() returns the column unchanged, so the parent's $instance->qualifyColumn($ownerKey) is already correct for MongoDB, and whereInMethod() is separately overridden to return whereIn instead of whereIntegerInRaw.

      Fix

      Remove the getResultsByType() override and inherit the Laravel implementation.

              Assignee:
              Jérôme Tamarelle
              Reporter:
              Jérôme Tamarelle
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Created:
                Updated: