mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/docs/drivers/php/laravel-mongodb/
MIT License
7k stars 1.43k forks source link

Trying to save an embedsMany relation results in the wrong query, fails. #2519

Open trip-somers opened 1 year ago

trip-somers commented 1 year ago

Description:

Attempting to store an embedded model via the embedsMany relationship results in an incorrect query causing the store to fail.

Steps to reproduce

  1. Create a parent model and collection. In this case, mine is called 'Organization' and looks like this:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;

class Organization extends Model
{
    use HasFactory;

    protected $connection = 'mongodb';
    protected $collection = 'organizations';

    protected $guarded = ['id', '_id'];

    public function paymentMethods()
    {
        return $this->embedsMany(PaymentMethod::class);
    }
}
  1. Create the embedded model. In this case, mine is called 'PaymentMethod' and looks like this:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;

class PaymentMethod extends Model
{
    use HasFactory;

    protected $guarded = ['id', '_id'];
}
  1. Attempt to store a new PaymentMethod for an Organization:
$organization->paymentMethods()->create($params);

Expected behaviour

A PaymentMethod document is embedded within the Organization document.

Actual behaviour

The following operation is executed. It tries to find an Organization with a PaymentMethod ID that matches the Organization's _id, creating an impossible condition.

organizations.UpdateMany(
    {"paymentMethods._id":"636aa6bf4bbb1badfa05c0e2"},
    {"$set":{
        "paymentMethods.$.updated_at":{"$date":{"$numberLong":"1677771653893"}},
        "paymentMethods.$.paymentMethods":[{
            "customer_id":239304,
            "remote_id":236547,
            "account_type":"visa",
            "account_last_4":"1111",
            "expiration_month":12,
            "expiration_year":2025,
            "billing_name":"Test",
            "updated_at":{"$date":{"$numberLong":"1677771653891"}},
            "created_at":{"$date":{"$numberLong":"1677771653891"}},
            "_id":"6400c38534e05e1b000214ba"
        }]
    }},
    {"multiple":true}
)
sampedraza commented 1 year ago

Did you ever figure this out? Running into a similar issue.

trip-somers commented 1 year ago

Nope. We wound up using a MongoDB anti-pattern and putting the PaymentMethod model in its own table. I have avoided using this package when I can. I assume there's a fork out there somewhere that fixes this, but I haven't looked for it yet.

omarherri commented 9 months ago

Did you ever figure this out? Running into a similar issue.

It works when you use create or update but not with save.