skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. The simplest solution is to maintain a parent reference, it will handle inverse relationships in MongoDB with Laravel:

    class Book extends Model
    {
        protected $fillable = ['title', 'user_id'];
    
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    
    class User extends Model
    {
        public function books()
        {
            return $this->embedsMany(Book::class);
        }
    
        public function addBook(Book $book)
        {
            $book->user_id = $this->_id;
            $this->books()->save($book);
        }
    }
    

    Usage:

    // Create and save a book
    $user = User::first();
    $book = new Book(['title' => 'My Book']);
    $user->addBook($book);
    
    // Get the parent user
    $book = Book::first();
    $user = $book->user;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search