'How to get pivot data in laravel lighthouse?
I use lighthouse package for making my graphql schema (https://github.com/nuwave/lighthouse)
But how to get data from @belongsToMany
relationship that is stored in pivot table?
E.g. the Document
entity connected N-N to Person
entity. And each Person has some meta data in the pivot table.
foreign_citizens: [Person!] @belongsToMany(relation: "foreignCitizens"),
Solution 1:[1]
At first you need to get your pivot data in laravel using withPivot
at the end of the relation, sth like this:
public function foreignCitizens(): BelongsToMany
{
return $this->belongsToMany()->withPivot(/* here is a list of your pivot data */);
}
Then you need to define the appropriate type
in graphql:
type ForeignCitizenPivot {
# Here goes the same list again
}
Then add a pivot
to your ForeignCitizen
type in graphql again:
type ForeignCitizen {
# other attributes
pivot: ForeignCitizenPivot
}
Solution 2:[2]
If it's simple data, I like to use model accessors. So, for example, you could add something like this to the model for your metadata.
function getMetaDataItemAttribute() {
return $this->pivot->meta_data_item;
}
Then in the Graph Schema, if it was a string, for example, you can reference it as a direct property.
type ForeignCitizen {
# other attributes
meta_data_item: String
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alireza A2F |
Solution 2 | Karl Hill |