Laravel-mongodb: How to store relation id as object id?

Created on 25 May 2017  路  5Comments  路  Source: jenssegers/laravel-mongodb

@jenssegers
I hope you are doing good!

I have an issue with relationship id, which is store as string.

How I can store that companyId as Object id?

$user = new User;
$user->companyId = $companyId;
$user->save();

Most helpful comment

$user->companyId = new MongoDB\BSON\ObjectId($companyId);

All 5 comments

any solutions?

I was looking into that briefly a while ago and didn't find a quick solution without having to extend or rewrite the library (and large parts of it when you're dealing with many-to-many relations). The issue is that the foreign key assignment goes through the normal accessors and converts ObjectId's to strings.

In addition to that Eloquent uses the id as an array index at some point while managing the relations which doesn't work if the foreign keys aren't strings or integers.

Might look into it again in the future but might not be able to find a solution. The main issue for us was not being able to use lookups during aggregation since MongoDB can't automatically convert between string and object ids.

It would probable require a major change to the functionality of the library basically making it incompatible with data of the current version and thus not be developed. Just speculating though.

$user->companyId = new MongoDB\BSON\ObjectId($companyId);

That only works on one-to-many relations, not many-to-many and also means you have to manually store the foreign key.

If a customer can have many users and a user can belong to many customers it stores the ids on both models as an array of strings. And it will crash when loading the relations if you try to manually store them as ObjectIds instead. At least with this kind of relation it is not possible to use the relation functionality of the ORM at all if you need the foreign keys to be stored as objects.

I also believe that a major change is required to achieve this.

I did it in a project I'm working on by extending almost all the relationship classes (like BelongsToMany, HasMany, etc), and overwriting their getParentKey() method (to return a MongoDB\BSON\ObjectId instance), as well as the BelongsToMany::attach(), BelongsToMany::buildDictionary() among other methods.

I'm sure my implementation does not cover all the functionality of relationships, so I will work on it from time to time.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kschethan picture kschethan  路  3Comments

HassanIbrahim picture HassanIbrahim  路  3Comments

Idnan picture Idnan  路  3Comments

yupangestu picture yupangestu  路  3Comments

pirmax picture pirmax  路  3Comments