Behnam Azimi
Behnam Azimi

Reputation: 2488

Special where on embedded relations - Laravel MongoDB

I have the following users collection:

{
  "type": "provider",
  "name": "user name",
  "username": "username",
  "password": "$2y$10$D3z0tLwOwB0tqPEnl63VuexOwqcR75QkVILemB1.TEsAJlk6Ixwim",
  "specialties": [
      "specialty 1",
      "specialty 2"
  ]
}

and a specialties collection :

{
  "_id": "5b26103b2df243228c0003ea",
  "title": "specialty 1",
  "description": "specialti 1 desc",
},{
  "_id": "5b26103b2df243228c0003ea",
  "title": "specialty 2",
  "description": "specialti 2 desc",
},

The relation between them is embedded-many and here is my relationship in User model,

public function specialties()
{
    return $this->embedsMany(Specialty::class, 'specialties', 'title');
}

I want to filter the users by specialty. For example, the above JSON user object should be returned if the filtered specialty is "specialty 1".

I know about non-embedded collections but my data is saved on my database and I cannot not change the schema.

Are there any alternative solutions?

Upvotes: 0

Views: 807

Answers (1)

Behnam Azimi
Behnam Azimi

Reputation: 2488

The solution was in the documentation, MongoDB specific operators,

In my case, the answer is,

$providers = User::where('specialties', 'all', ['specialty 1'])->with('s_specialties')->get();

This code simulates $in operator in MongoDB. More about operators.

Upvotes: 1

Related Questions