繁体   English   中英

如何在laravel灯塔中获取pivot数据?

[英]How to get pivot data in laravel lighthouse?

我使用灯塔 package 制作我的 graphql 架构 ( https://github.com/nuwave/lighthouse )

但是如何从存储在 pivot 表中的@belongsToMany关系中获取数据呢?

例如, Document实体将 NN 连接到Person实体。 每个人在 pivot 表中都有一些元数据。

foreign_citizens: [Person!] @belongsToMany(relation: "foreignCitizens"),

首先,您需要在关系末尾使用withPivot获取 laravel 中的 pivot 数据,如下所示:

public function foreignCitizens(): BelongsToMany
{
  return $this->belongsToMany()->withPivot(/* here is a list of your pivot data */);
}

然后需要在graphql中定义合适的type

type ForeignCitizenPivot {
  # Here goes the same list again
}

然后再次将 pivot 添加到pivot中的ForeignCitizen类型:

type ForeignCitizen {
  # other attributes
  pivot: ForeignCitizenPivot 
}

如果是简单的数据,我喜欢使用 model 访问器。 因此,例如,您可以将类似这样的内容添加到元数据的 model 中。

function getMetaDataItemAttribute() {
    return $this->pivot->meta_data_item;
}

然后在 Graph Schema 中,如果它是一个字符串,例如,您可以将其作为直接属性引用。

type ForeignCitizen {
    # other attributes
    meta_data_item: String 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM