hasMany relationship return null with mongodb (jenssegers) laravel

829 Views Asked by At

i have laravel 8 project with jenssegers (Mongodb Database) but my hasMany relationship not work between Product & Category Model my Product mongo object :

{
"_id" : ObjectId("5dcaafb8eaec3701a2774d29")
"category_ids" : [ 
    ObjectId("5dcaacbfeaec37018b508a39"), 
    ObjectId("5dcaacbfeaec37018b508a5d")
]}

and my Category mongo object :

{
"_id" : ObjectId("5dcaacbfeaec37018b508a39"),
"title" : "category test",
"slug" : "wordpress-plugins"

}

my Product model code :

public function categories() {
    return $this->hasMany(Category::class, 'category_ids', '_id');
}

but below code return null :

$product = Product::with('categories')->where('_id', $id)->first();
    dd($product->categories);

please help me , thanks :)

2

There are 2 best solutions below

0
On

You need to use $this->belongsToMany relation in both the modals.

public function categories() {
   return $this->belongsToMany(Category::class);
}

public function products() {
   return $this->belongsToMany(Product::class);
}
0
On

Well, because you added category_ids in product field, I suppose you mean Product belongs to many Categories, and each Category can have many Products attached to it. So the relationship should be declared differently. That is:

  • Create a pivot Model CategoryPost with table/collection categories_posts
  • Let the collection categories_posts store product_id and category_id to show that a Product belongs to that Category (instead of saving the category ids in product collection as array)
  • Define your relationship in Product Model as follows
// This is what you should rather have in your Product Model
public function categories() {
   return $this->belongsToMany(Category::class, 'categories_products', 'product_id', 'category_id');
}

// While in your Category Model, you can have this if you wish to get all products belonging to a category using the Category instance
public function products() {
   return $this->belongsToMany(Products::class, 'categories_posts', 'category_id', 'product_id');
}