Search code examples
laravelmongodbrelation

Laravel MongoDB 1:n relations


What is the correct way of defining 1:n relations in Laravel using MongoDB between two models Author and Book where one author can have several books while one book has exactly one authors?

Author.php

class Author extends Model
{
    public function books()
    {
        // what to place here?
        return $this->...
    }
}

Book.php

class Book extends Model
{
    public function author()
    {
        // what to place here?
        return $this->...
    }
}

Controller.php

class BookController extends Controller
{
    public function store (Author $author, Request $request)
    {
        $book1 Book::create();
        $book2 Book::create();

        // connect $book1 <-> $author and $book2 <-> $author
        // what to place here?

        $book1->save();
        $book2->save();
    }
}

After calling store() I want to be able to do the following request

dump ($book1->author); // return $author
dump ($author->books); // return Collection of $book1 and $book2

Solution

  • assume you have the foreign key author_id in books table

    class Author extends Model
    {
        public function books()
        {
            return $this->hasMany(Book::class, 'author_id');
        }
    }
    
    class Book extends Model
    {
        public function author()
        {
            return $this->belongsTo(Author::class, 'author_id');
        }
    }
    
    class BookController extends Controller
    {
        public function store (Author $author, Request $request)
        {
            $book1 = new Book();
            $book2 = new Book();
    
            $author->books()->saveMany([$book1, $book2]);
        }
    }