mongodb relational models in laravel

25 Views Asked by At

I'm using mongodb in laravel with laravel-mongodb package. Models have Eloquent relations of One to One and One to Many. Here's is one example of two models having One to Many relation.

User Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MongoDB\Laravel\Eloquent\Model;

class User extends Model
{
    use HasFactory;
    protected $connection = 'mongodb';
    protected $collection = 'users';
    protected $guarded = [];


    public function books() {
        return $this->hasMany(Book::class);
    }
}
?>

Book Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MongoDB\Laravel\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
    protected $connection = 'mongodb';
    protected $collection = 'books';
    protected $guarded = [];


    public function books() {
        return $this->belongsTo(User::class);
    }
}
?>

Now when I save relational data, the userId saved as string instead of ObjectId of user model.

$book = User::find('660295901f99a91a5b046d63')->book()->save(new Book(array('name' => 'xyz'));

MongoDB document save like this.

{
  "_id": {
    "$oid": "660295921f99a91a5b046d64"
  },
  "userId": "660295901f99a91a5b046d63",
  "name": "xyz
}

my question is how to save userId as ObjectId not as string.

If I wrap userId in ObjectId using **use MongoDB\BSON\ObjectId ** then it saved as ObjectId but then Eloqeunt does not retrieve relational data.. it only retrieve data if refernece key was saved as string.

As ObjectId has advantage over string type. so does it make sense to save reference key as ObjectId?

Any help would be appreciated.

0

There are 0 best solutions below