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?
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;