laravelmongodbjenssegers-mongodb

Why laravel returns an empty array for a has many relationship?


I am using jenssegers/laravel-mongodb and i have schema is like below

Ticket Collection :

{
      "_id": ObjectId("5f32d9bb486e94459b6531c3"),
      "subject": "\"URGENT\" Non-Compliance In (Eastern Region)",
      "content": "abc",
      "user_team": "5f044199e40dfe4847056785",
      "team_ids": [
        "5f3012bbb7c2bc422e4da5a2"
      ],
      "organization_id": "5f74359c7dcc8f6fbb2b47e2"
}

Team Collection :

{
      "_id":ObjectId("5f3012bbb7c2bc422e4da5a2"),
      "name": "Medical Maintenance",
      "createTickets": true
}

Relationship in Ticket Model :

public function teams()
    {
         return $this->HasMany('App\Team', 'team_ids');
    }

Relationship in Team Model :

public function ticket()
    {
        return $this->belongsTo('App\Ticket');
    }

I am facing an issue to get data for teams relationship. It return an emtpry array.

Laravel version is 6.2 jenssegers/mongodb version is 3.6


Solution

  • Your approach to the foreign key is wrong, when in the context of hasMany. Instead a single column called team_id should be on the ticket and then you can do the following.

    public function teams()
    {
         return $this->HasMany('App\Team', 'team_id');
    }
    

    Which would work if your ticket looks like so.

    {
          "_id": ObjectId("5f32d9bb486e94459b6531c3"),
          "subject": "\"URGENT\" Non-Compliance In (Eastern Region)",
          "content": "abc",
          "user_team": "5f044199e40dfe4847056785",
          "team_id":"5f3012bbb7c2bc422e4da5a2"
          "organization_id": "5f74359c7dcc8f6fbb2b47e2"
    }
    

    Instead it looks like you are actually doing a many to many, because one team can have many tickets and reverse. This can be defined like so, this will probably add the data to both models, but I'm not an expert on Mongodb in Laravel.

    public function teams()
    {
        return $this->belongsToMany(
            Team::class, null, 'ticket_ids', 'team_ids'
        );
    }
    

    You can find all of this in the documentation.