laravel hasMany relation didnot work with mongodb database

Updated: Feb 18, 2025

laravel hasMany relation didnot work with mongodb database

Laravel's Eloquent ORM provides a powerful and flexible way to define relationships between models when working with traditional relational databases like MySQL or PostgreSQL. However, when it comes to using MongoDB with Laravel, the built-in Eloquent relations might not work out of the box. In this answer, we will discuss the hasMany relation and how to make it work with MongoDB using Laravel's MongoDB package.

First, let's make sure we have Laravel installed with the laravel/mongodb package. You can install it via composer:

composer require laravel/mongodb

Next, let's define our models. For this example, let's assume we have two models: Post and Comment. A Post has many Comments.

// app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Post extends Model
{
    protected $connection = 'mongodb';

    protected $collection = 'posts';

    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id');
    }
}

// app/Models/Comment.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $connection = 'mongodb';

    protected $collection = 'comments';

    protected $fillable = ['content'];

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }
}

Notice that we set the connection and collection names for both models. Also, we define the hasMany relation on the Post model and the belongsTo relation on the Comment model.

Now, let's test the relationship. First, let's create a new post and some comments:

php artisan make:model Post --model=App/Models/Post --connection=mongodb
php artisan make:model Comment --model=App/Models/Comment --connection=mongodb

php artisan db:seed --class=DatabaseSeeder

In your DatabaseSeeder class, add the following code to create some data:

use App\Models\Post;
use App\Models\Comment;

public function run()
{
    $post = Post::create([
        'title' => 'My first post',
    ]);

    Comment::create([
        'content' => 'Great post!',
        'post_id' => $post->id,
    ]);

    Comment::create([
        'content' => 'Another comment',
        'post_id' => $post->id,
    ]);
}

Now, let's test the relationship:

$post = Post::with('comments')->find(1);

foreach ($post->comments as $comment) {
    echo $comment->content;
}

This should output the contents of both comments associated with the post.

In summary, to make the hasMany relation work with MongoDB in Laravel, you need to define the relationship in your models, set the connection and collection names, and ensure that the foreign key is present in the related model. Additionally, you might need to use the with method when querying the parent model to eager-load the related records.