mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/compatibility/mongodb-laravel-integration
MIT License
6.99k stars 1.42k forks source link

How to retrieve models from a list of id in a document ? #1387

Closed MickaelAmar closed 4 years ago

MickaelAmar commented 6 years ago

Hello,

I'm currently trying to build a relationship to retrieve a list of Ingredients in my Recommendation model but it doesn't seem to work and I'm starting to think that my data organization isn't made to suits Laravel features.

How can I retrieve all the ingredients models contained in the results array of a Recommendation ? Is a pivot table mandatory at this point ?

Recommendation Model

 class Recommendation extends Moloquent
    {
        protected $collection = 'recommendations';

        public function ingredients()
        {
            return $this->hasMany(Ingredient::class, 'results.ingredient_id', '_id');
        }
    }

Ingredient Model

class Ingredient extends Moloquent
    {
        protected $collection = 'ingredients';

        public function recommendation()
        {
            return $this->belongsTo(Recommendation::class);
        }
    }

JSON format Recommendation

{
       "_id" : ObjectId("123"),
       "user_id" : "321",
       "results" : [ 
          {
            "ingredient_id" : "1",
            "selected" : true
          }, 
          {
            "ingredient_id" : "2",
            "selected" : false
          }, 
          ...
        ]
     }

JSON format Ingredient

 {
        "_id" : "1",
        "name" : "Phthalates",
        "description" : "Phthalates are a group of..."
    }
MickaelAmar commented 6 years ago

I realized this can only be done through a ManyToMany relationship. Check this link.

hasMany method doesn't allow mongodb documents to be used with an array of id. Therefore, the related collection should contain 1 document per related id if you want to use the relationship properly.