Laravel Lighthouse retrieving pivot data

539 Views Asked by At

I'm using Laravel Lighthouse v4.16 to write the API for my project. Most of the mutations and queries work fine. But when I try to query for pivot data the results indicate that all pivot data is null.

So we have 3 different models I'll only show the relationship causing problems

User

public function companies(): BelongsToMany {
    return $this->belongsToMany(Company::class)
        ->using(CompanyUser::class)
        ->withPivot(
            'personnel_number',
        );
}

Company

public function users(): BelongsToMany {
   return $this->belongsToMany(User::class)->withPivot(
      'personnel_number',
   )->using(CompanyUser::class);
}

CompanyUser - extends pivot

public function user(): BelongsTo {
    return $this->belongsTo('App\Models\Tenant\User', 'user_id');
}

public function company(): BelongsTo {
    return $this->belongsTo('App\Models\Tenant\Company', 'company_id');
}

These are represented as the following types in Graphql

type User {
    id: ID!
    title: String
    companies: [Company!] @belongsToMany
    pivot: CompanyUser
}

type Company {
    id: ID!
    name: String
    users: [User] @belongsToMany
}

type CompanyUser {
    id: ID!
    personnel_number: String
    user: User! @belongsTo
    company: Company! @belongsTo
}

But when I run the following query the relationship is retrieved successfully but the pivot remains null.

{
 user(id: 1) {
    id
    first_name
    companies {
      id
      name
    }
    pivot {
      personnel_number
    }
  }
}

The result of that query looks like the one below

{
  "data": {
    "user": {
      "id": "1",
      "first_name": "Mike",
      "companies": [
        {
          "id": "1",
          "name": "company_name_1"
        }
      ],
      "pivot": null
     }
   }
}
1

There are 1 best solutions below

0
On

The problem is the location of the pivot in your query, the pivot should be inside a relation ( ie: it is gonna be loaded after the join of the table is made to load the relation ).

So in order to achieve that, you need to make those changes:

  • in the type:
type Company {
    id: ID!
    name: String

    users: [User] @belongsToMany
    pivot: CompanyUser # add
}
  • in the query:
{
  user(id: 1) {
    id
    first_name
    companies {
      id
      name
      pivot { # moved here, inside companies relations
        personnel_number
      }
    }
  }
}

A remarque : you could manipulate the pivot data without having the CompanyUser class.