mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/compatibility/mongodb-laravel-integration
MIT License
6.96k stars 1.42k forks source link

fix attributeToArray method #3024

Closed florianJacques closed 1 day ago

florianJacques commented 3 days ago

When dealing with embedded models with relationships (EmbedOne and/or EmbedMany), the serialization methods do not serialize Mongo BSON types in nested fields, as the function only converts top-level attributes.

In the exemple, prices is embedMany Relationship

 public function prices(): EmbedsMany
 {
      return $this->embedsMany(Price::class, 'prices', 'product');
 }

Before fix =>

 [
    "_id" => "667be7212ea8e4cc8b0dd636",
    "isActive" => true,
    "name" => "CREDIT_PACKAGE_3",
    "category" => "CREDIT_BALANCE",
    "quantity" => 3.0,
    "prices" => [
      [
        "currency" => "EUR",
        "price" => 5.99,
        "_id" => MongoDB\BSON\ObjectId {#4456
          +"oid": "667be7212ea8e4cc8b0dd634",
        },
      ],
    ],
]

After fix =>

 [
    "_id" => "667be7212ea8e4cc8b0dd636",
    "isActive" => true,
    "name" => "CREDIT_PACKAGE_3",
    "category" => "CREDIT_BALANCE",
    "quantity" => 3.0,
    "prices" => [
      [
        "currency" => "EUR",
        "price" => 5.99,
        "_id" => "667be7212ea8e4cc8b0dd634",
      ],
    ],
]
GromNaN commented 3 days ago

Thank you @florianJacques for contributing. To review your PR correctly, I need that you describe the issue, and if possible add tests validating the fix.

florianJacques commented 3 days ago

Thank you @florianJacques for contributing. To review your PR correctly, I need that you describe the issue, and if possible add tests validating the fix.

Test ok