【问题标题】:Laravel Lighthouse Graphql HasOne nested relation not workingLaravel Lighthouse Graphql HasOne 嵌套关系不起作用
【发布时间】:2020-04-20 03:15:12
【问题描述】:

我正在尝试建立 HasOne 关系以在 Laravel Lighthouse GraphQL 中工作。
它不起作用。突变不会给出错误,但也不会更新关系(员工 id 保持不变,而我希望它更改为 2):

mutation {
  updateAccount(input: {
    id: 12
    employee: {
      connect: 2
    }
  }) {
    id
    employee {
      id
    }
  }
}

我的架构如下所示:

type Mutation {
    updateAccount(input: UpdateAccount! @spread): Account! @update
}

input UpdateAccountInput {
    id: ID!
    employee: CreateEmployeeRelationInput @hasOne
}

input CreateEmployeeRelationInput {
    connect: ID!
}

type Account {
    id: ID!
    ...
    employee: Employee! @hasOne
}

type Employee {
    id: ID!
    ...
    account: Account @belongsTo
}

Account 和 Employee 模型如下所示:

class Account extends Model
{
    public function employee(): HasOne
    {
        return $this->hasOne(\App\Models\Employee::class, 'account_id');
    }
}

class Employee extends Model
{
    public function account(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Account::class, 'account_id');
    }
}

任何帮助或建议将不胜感激。
到目前为止,我尝试添加/删除@hasOne,或将ID! 更改为[ID!]!,但没有任何效果。

【问题讨论】:

  • 您的AccountEmployee 类型是什么样的?
  • 我已将AccountEmployee 类型添加到问题中(仅显示相关的字段)。这些类型会有什么不同吗?
  • 我在您的代码中看到的唯一与我的不匹配的是您在输入中使用了@hasOne 指令。
  • 你确定是一样的吗?如果我正确阅读了文档,那么我尝试做的事情在 Lighthouse 中是不可能的。我在这里打开了一个问题:github.com/nuwave/lighthouse/issues/1109

标签: laravel graphql laravel-lighthouse


【解决方案1】:

我发现 Lighthouse 没有提供我想要的功能,因为 Laravel 没有提供它,而 Lighthouse 试图镜像 Laravel 的功能。

更多信息可以在这个问题的答案中找到:https://github.com/nuwave/lighthouse/issues/1109#issuecomment-570544848

简而言之:
hasOne 关系associate()dissociate() 方法。
hasMany 关系sync()attach()detach()
但是belongsTo 关系确实associate()dissociate()

因此,如果帐户 hasOne 员工,我会这样做:

mutation {
  updateAccount(input: {
    id: 12
    employee: {
      connect: 2
    }
  }) {
    id
    solis_id
    employee {
      id
    }
  }
}

另外,如果一个帐户有很多员工,我可以这样做:

mutation {
  updateAccount(input: {
    id: 12
    employees: {
      connect: [2, 3]
    }
  }) {
    id
    solis_id
    employees {
      id
    }
  }
}

但我可以达到同样的结果是这样的:

mutation {
  updateEmployee(input: {
    id: 2
    account: {
      connect: 2
    }
  }) {
    id
    account {
      id
    }
  }
}

【讨论】:

  • 伙计,我也遇到了同样的问题,但我无法解决:(
  • @mentamarindo 祝你好运!我将无法提供帮助,因为我停止使用 PHP for GraphQL(切换到 JS,这并不容易)。
  • 如果JS不简单为什么要切换?
  • 好问题。主要是因为我发现我更喜欢 JavaScript。我选择了 Nexus+Prisma,它对我来说看起来很有希望(对一件事的完整打字稿支持),但它的边缘仍然很粗糙。
猜你喜欢
  • 2020-08-18
  • 2015-04-02
  • 1970-01-01
  • 2020-05-01
  • 2022-07-12
  • 2020-10-06
  • 2017-01-24
  • 1970-01-01
  • 2020-09-29
相关资源
最近更新 更多