mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Home Page:https://www.mongodb.com/compatibility/mongodb-laravel-integration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for morphTo relations broken in 4.1

apeisa opened this issue · comments

  • Laravel-mongodb Version: 4.1.dev
  • PHP Version: 8.2.11
  • Database Driver & Version: 1.16.2 (6.0.3)

Description:

There has been working support for morphTo relations, but that seems to break after upgrading from 4.0 to 4.1.

Steps to reproduce

  1. You need to have model with morphTo relationship. Here is my "Subscription" model (it does extend mongo model, leaving namespaces out for simpllicity):
class Subscription extends Model
{
    use HasFactory;

    public function subscribable(): MorphTo
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
  1. When using the relationship it fails. This is how this is used in our codebase (controller):
$subscription = new Subscription();
$subscription->user()->associate($user);
$subscription->subscribable()->associate($thread);
$subscription->save();

Expected behaviour

New subscription should be saved to database with this kind of values:

{
  "_id": {
    "$oid": "647ee3c2ef95cab3850d4ee9"
  },
  "user_id": "64637d18a21fdb655d09bc83",
  "subscribable_id": "647ee3c2ef95cab3850d4ee8",
  "subscribable_type": "App\\Models\\Thread",
  "updated_at": {
    "$date": "2023-06-06T07:44:02.589Z"
  },
  "created_at": {
    "$date": "2023-06-06T07:44:02.589Z"
  }
}

Actual behaviour

InvalidArgumentException is thrown: First argument of MongoDB\Laravel\Query\Builder::where must be a field path as "string". Got "null"

Here is more detailed stacktrace: https://flareapp.io/share/bP99dGOP

I also noticed that MorphTo relations are not listed as supported relations on the readme. They have worked nicely before though - so is it safe to assume these will be supported in the future too? Because if not, this would mean migrating away from Mongo in our current project.

Hi @apeisa, I was working on this issue today. I fixed it and I'm going to open a PR.

Thanks for your feedback @apeisa, it's great to have contributors testing development branches. It helps us deliver stable releases without regression.
We're going to make sure there's no regression with MorphTo. This feature will be covered by tests from now on.

Great news and thanks for pull request. I will do further tests when it is merged.