0

There are two models: Restaurant and Category

Restaurant{
  '_id' : 12345678
  'name' : "xyz",
  'abstract' : "awdwadawdawdawd",
  'category': [1,2,3,4] //category ids
}

Category{
  '_id' : 1,
  'name' : 'PQR'
}

How can I assign relationship and fetch all the categories using that array field (category) of Restaurant in laravel 5.3 and Database is mongodb?

1 Answer 1

1

I am not quite sure about your DB structure, but I think it would be better to create a new pivot table to store the categories of each restaurant in a different row like this:

id | restaurant_id | category_id
1  | 23            | 3
2  | 23            | 5
3  | 25            | 4

As a convention the table should be named 'category_restaurant'

This would be a many to many relationship in laravel.

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

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

Then in your code you can get the ids of a restaurant in this way:

$restaurant = Restaurant::find(1);
$categories = $restaurant->categories;
Sign up to request clarification or add additional context in comments.

3 Comments

Here is the documentation about it: Many to many relationships.
Yeah sorry I didn't notice the Mongodb part. Not sure how to implement it in the Mongo.
Yes! I know this but I wanted to know how can I implement this using mongodb array field @isa424

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.