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

The withPivot fields are getting ignored. #1618

Open tzsk opened 6 years ago

tzsk commented 6 years ago

I have 2 Models Product & Size. They are ManyToMany related to each other.

Now, every Product will have different price with respect to the Size.

It is simple in Laravel:

$product->sizes()->sync(['foriegnKey' => ['price' => 200]])
// Here foriegnKey will be an integer for MySQL in default setup unless using UUID.

// I am doing the similar thing here with this package
$product->sizes()->sync(['sizeObjectId' => ['price' => 200]])

But this is not working. This is an URGENT FIX in my opinion. Because it is not working as it should be.

If you don't want to make use of Pivot Collection then you can put the IDS in an Object instead of an array. The object will be a Key-Value pair having the Object ID as key and the value being another Object with the Pivot Attributes.

Tell me, if I am approaching this scenario differently / wrongly than how MongoDB works. Is there any better solution to this scenario in MongoDB?

george-viaud commented 6 years ago

I think this may be related to #1628 - similar issue.

This is from the readme:

The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to `null`:

If I understand correctly, this is a real super weakness of the implementation in this lib and should be brought to work in a similar way to the standard tabular databases.

The created field x_ids would just become x_pivot or similar and would contain not only the IDs of the associated collection but also the pivot data.

I think you can achieve the same end-effect but with extra steps if you manually implement the pivot, but this is heavy / shows the weakness...

I wish I had better news but will subscribe to this thread in hopes an answer better than mine emerges as this is a major issue I would also like to see rectified.

Be well

AAllport commented 5 years ago

Hate to bump an old issue, but I'm currently working on an implementation that I intend to PR