[英]How to get pivot data in laravel lighthouse?
I use lighthouse package for making my graphql schema ( https://github.com/nuwave/lighthouse )我使用灯塔 package 制作我的 graphql 架构 ( https://github.com/nuwave/lighthouse )
But how to get data from @belongsToMany
relationship that is stored in pivot table?但是如何从存储在 pivot 表中的@belongsToMany
关系中获取数据呢?
Eg the Document
entity connected NN to Person
entity.例如, Document
实体将 NN 连接到Person
实体。 And each Person has some meta data in the pivot table.每个人在 pivot 表中都有一些元数据。
foreign_citizens: [Person!] @belongsToMany(relation: "foreignCitizens"),
At first you need to get your pivot data in laravel using withPivot
at the end of the relation, sth like this:首先,您需要在关系末尾使用withPivot
获取 laravel 中的 pivot 数据,如下所示:
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:然后需要在graphql中定义合适的type
:
type ForeignCitizenPivot {
# Here goes the same list again
}
Then add a pivot
to your ForeignCitizen
type in graphql again:然后再次将 pivot 添加到pivot
中的ForeignCitizen
类型:
type ForeignCitizen {
# other attributes
pivot: ForeignCitizenPivot
}
If it's simple data, I like to use model accessors.如果是简单的数据,我喜欢使用 model 访问器。 So, for example, you could add something like this to the model for your metadata.因此,例如,您可以将类似这样的内容添加到元数据的 model 中。
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.然后在 Graph Schema 中,如果它是一个字符串,例如,您可以将其作为直接属性引用。
type ForeignCitizen {
# other attributes
meta_data_item: String
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.