I’m using MongoDb/Laravel-MongoDb 5.* package for Laravel. In version 4 there was a documented inverse of embeded relationships which was "automagicly" added.
For example:
class User extends Model
{
public function books()
{
return $this->embedsMany(Book::class);
}
}
$book = Book::first();
$user = $book->user;
I suspect this went away since the move to 5.0/Mongo taking on maintenance of the package, but it is also a rather helpful feature. Am I missing something or is there another way to access this? Looking at the raw eloquent object, it doesn’t seem like the parent info is stored there, however you can save an embeded object so it must exist somewhere.
2
Answers
It seems like this feature has become undocumented, but does still automatically exist. I was trying to use it in an automated test where the parent wasn't being properly created, however once I got the child properly built, then the parent was accessible as the old documentation explained.
The simplest solution is to maintain a parent reference, it will handle inverse relationships in MongoDB with Laravel:
Usage:
This approach stores the parent ID in the embedded document, allows easy access to the parent document, is simple to implement and maintain, and works well for basic embedded relationships, though it requires storing an additional field (user_id) in each embedded document.