Collection One User:
{
"_id": ObjectId("52b6bd7ad6861b6101000003"),
"name": "John Doe",
"updated_at": ISODate("2013-12-22T10:22:50.180Z"),
"created_at": ISODate("2013-12-22T10:22:50.180Z")
}
Collection Two Role:
{
"_id": ObjectId("52b6bd7ad6861b6101000006"),
"type": "sword",
"user_id": ObjectId("52b6bd7ad6861b6101000003"),
"updated_at": ISODate("2013-12-22T10:22:50.189Z"),
"created_at": ISODate("2013-12-22T10:22:50.189Z")
}
If user saved as string on Role collection then all relation is working fine. But its not working when reference id is saved as ObjectId. Is there any way to make it work?
Why are you using ObjectId?
My exist database is in that structure.
If your relations are set up correctly, you can attach models as described here: http://laravel.com/docs/eloquent#inserting-related-models
$comment = new Comment(array('message' => 'A new comment.'));
$post = Post::find(...);
$comment = $post->comments()->save($comment);
Or manually like:
$post = Post::find(...);
$comment = Comment::create(array('message' => 'A new comment.', 'post_id' => $post->_id));
Actually saving data is not my concern. It will work any of the method you point out. My concern is retrieving the data like
Post::find(...)->comments();
Use $post->comments, because $post->comments() returns the query builder.
Yes $post->comment. But it's nor working when the post_id on comments collection is ObjectId.
Indeed, it seems that items.find({"user_id":"52b9505281fec66d6e0041a7"}, []) does not work if the id is saved as MongoId.
But I don't know if it will be easy to make it work. If the id's are stored as string, and you search based on MongoId like items.find({"user_id":{"$id":"52b9524181fec6916f0041a7"}}, []) it won't work either.
Any workaround for this?
For the application where data is produced by Nodejs or any other framework, it stores relationship as ObjectId('related model id'),
In my case I am using database where Related model id are stored as MongoDbBSON\ObjectID().
NON of Moloquent relationship working
@talukdar here is your solution,
$userFiles = UserFile::whereIn('directory_id',$userDirectories->map(function($dir){
return new \MongoDB\BSON\ObjectID($dir->directory_id);
}))->get();
However you'll not be able to use any Eloquent/Moloquent Relationships in these type of case as described by @Chintan7027
I just ran into the same issue, 8 years later. How is this still a thing? Referencing by object id's is preferred in mongo, I would expect relations to work with them just as well
Most helpful comment
Any workaround for this?