首页 > 解决方案 > GraphQL - 模型属于特定用户字段

问题描述

我正在使用Lighthouse包来实现 GraphQL,我的应用程序中的用户属于一个实体,我需要获取属于每个用户实体的模型,我的架构目前是这样的

"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

type Query {
    me: User @auth
    execution: [RobotTime!]! @all
}

type RobotTime {
    id: ID!
    instance: Instance!
    robot: Robot!
    start: DateTime!
    end: DateTime!
}

type Instance {
    id: ID!
    name: String!
    token: String!
}

type Robot {
    id: ID!
    start_bot: String!
    process: Process!
}

type Process {
    id: ID!
    name: String!
    token: String!
}
type User {
    id: ID!
    name: String!
    email: String!
    created_at: String!
    updated_at: String
}

我已经搜索了文档,但找不到任何可以帮助我做我需要做的事情的东西。

目前我已经在一个控制器中完成了它,我将它作为一个逻辑不那么复杂的 json 返回,我使用了大约 5 个模型。

对不起,我的英语不好

标签: laravelgraphqllaravel-lighthouse

解决方案


您需要User在 laravel 中的模型中声明适当的关系,如下所示:

public function entity(): BelongsTo
{
    return $this->belongsTo(Entity::class);
}

然后User在graphql中添加type中的关系:

type User {
    id: ID!
    name: String!
    email: String!
    created_at: DateTime!
    updated_at: DateTime

    entity: Entity @belongsTo
}

当然,你需要Entity在 laravel 中声明一个模型并输入 graphql。


推荐阅读