首页 > 解决方案 > 如何在 Laravel 灯塔中查询第三方包特征

问题描述

我阅读了 Laravel Lighthouse 文档并在网上搜索,但没有找到如何在 Laravel 的第三方包中查询特征。我正在使用qirolab/laravel-reactions包,它具有reactSummary ()特性。我在问如何在灯塔查询中添加这种关系?

type Post {
    id: ID!
    title: String!
    excerpt: String!
    image_url: String!
    slug: String!
    source: Source! @belongsTo
    reactionSummary: ???????
    created_at: DateTime!
    updated_at: DateTime!
}

除了解决我的问题之外,我的问题还有一个目的,了解 lighthouse 如何使用包或如何将第三方包与 lighthouse 集成?

标签: laravelgraphqllaravel-lighthouse

解决方案


您需要在 graphql 中定义反应模型的模式,在后模式中您需要定义反应类型的数组。

根据模型(https://github.com/qirolab/laravel-reactions/blob/master/src/Models/Reaction.php),反应graphql模式看起来像这样:

type Reaction {
   reactBy: User! @belongsTo
   type: String
   reactable: Reactable! @morphTo
}

您的帖子架构将更改为

type Post {
    id: ID!
    title: String!
    excerpt: String!
    image_url: String!
    slug: String!
    source: Source! @belongsTo
    reactionSummary: [Reaction]
    created_at: DateTime!
    updated_at: DateTime!
}

正如我从迁移文件https://github.com/qirolab/laravel-reactions/blob/master/migrations/2018_07_10_000000_create_reactions_table.php中看到的那样。该反应具有多晶型关系。

这意味着返回类型可能会根据reactable_type字段中设置的模型类型而有所不同。因此,您需要定义自己的 Union 类型。

联合是一种简单枚举其他对象类型的抽象类型。它们类似于接口,因为它们可以返回不同的类型,但它们不能定义字段。

来源:https ://lighthouse-php.com/5/the-basics/types.html#union

另请参阅多态关系和联合部分:https ://lighthouse-php.com/5/eloquent/polymorphic-relationships.html#one-to-one

我希望这能为您提供有关如何进行的方向。


推荐阅读