0

I'm Using jenssegers/laravel-mongodb library in my Laravel MongoDB application. However, the hasOne relationship is only working if foreignKey in a string. if it saves as a ObjectId type, the relationship gives an empty result.

MongoDB document user_profile

{
    "_id" : ObjectId("5c40307107928879107d8ee3"),
    "first_name" : "Alert",
    "last_name" : "CB",
    "speciality" : null,
    "company" : ObjectId("5b8cd8bc0176533ff65c4c62"),
    "platform_start_date" : "2019-01-17",
    "updated_at" : ISODate("2019-01-17T13:40:37.000+05:30"),
    "created_at" : ISODate("2019-01-17T13:06:17.000+05:30")
}

Company document

{
    "_id" : ObjectId("5b8cd8bc0176533ff65c4c62"),
    "name" : "ABCDEF",
    "contact" : "Dani",
    "notes" : "Test Note for builders....",
    "updated_at" : ISODate("2018-09-03T12:16:20.000+05:30"),
    "created_at" : ISODate("2018-09-03T12:16:20.000+05:30")
}

In UserProfile model

class UserProfile extends Moloquent
{
public function companies() {
        return $this->hasOne('App\Models\Company', 'company', '_id' );
    }

Currently this companies() give empty array, How to solve this and get the results ? I'm using jenssegers/mongodb: 3.4.2

Miuranga
  • 2,463
  • 10
  • 51
  • 81
  • Can you swap the localkey and foreignkey parameters and try again? – Taha Paksu Jan 08 '21 at 07:07
  • @TahaPaksu it will give exception "Illegal offset type in isset or empty" in the controller that related to this – Miuranga Jan 08 '21 at 07:15
  • 1
    Did you try it before? HasMany relation had these parameters reversed, maybe moloquent implemented that in the reverse order too. – Taha Paksu Jan 08 '21 at 07:25
  • @TahaPaksu yes, This is working when company foreignkey is a string. but if it ObjectId, gives empty. – Miuranga Jan 08 '21 at 07:57
  • Then convert it to string when saving it? (the company field) Guess it has something to do with indexing? – Taha Paksu Jan 08 '21 at 08:08
  • @TahaPaksu Yes, we need indexing. That's why try to do this. – Miuranga Jan 08 '21 at 08:33
  • 2
    Well after some research, the most reliable way would use a string column to build the relation, and add the index to it. This library doesn't support relations with ObjectId, but you can use aggregate queries with it. But it won't have the relation features. – Taha Paksu Jan 08 '21 at 08:49

0 Answers0