2

i am using laravel mongodb collection in that i have some relationship issues here is my collection of user in which user have multiple addresses and addresses is save in another collection and that ids is save in user collection

{
 "_id":ObjectId("52ffc33cd85242f436000001"),
 "contact": "987654321",
 "dob": "01-01-1991",
 "name": "Tom Benzamin",
 "address_ids": [
  ObjectId("52ffc4a5d85242602e000000"),
  ObjectId("52ffc4a5d85242602e000001")
    ]
}

for getting user information and his addresses information i have to make 2 query one for user and other for addresses

can it is possible to get user info with addresses in single query by using eloquent relationship. Sorry i am new in mongodb collection.

1
  • 1
    Where you able to find a solution for this ? I am facing the same issue Commented Jan 4, 2018 at 12:05

1 Answer 1

2

You don't need to save the document id's of addresses in the user document like that for what you are trying to achieve. Laravel is all about clean code, that ain't clean.

Make the following relationships:

  • User > hasMany > Addresses

  • Addresses > belongsTo > User

To load a user object in Laravel including all address objects use eager loading (https://laravel.com/docs/5.3/eloquent-relationships#eager-loading).

You can write eloquent query as followed in PHP:

User::where(...some condition...)->with('addresses')->get();

Best Regards,

bdschr

Sign up to request clarification or add additional context in comments.

1 Comment

Specifically can try out "whereHas" and "with" QueryRelations from eloquent.

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.