lighthouse php 使用 eloquent 模型访问器和修改器

问题描述

我在 Laravel 应用程序之上使用了用于 graphql 的灯塔。我知道如何定义类型。但是如何在模式的类型定义中使用模型访问器?例如,我有这样的类型使用

type User {
   id: ID!
   name: String
}

但是我在数据库表中没有 name 列,但是我的 eloquent 模型中有一个名称访问器,我想在这种情况下使用它而不是奇怪的列名。有什么办法可以使用模型访问器吗?

解决方法

你的意思是像 getFirstNameAttribute 这样的方法吗?只需在您的方案中定义一个蛇形字段,就我而言,它将是 first_name: String

type User {
   #...
   first_name: String
}
,

如果您使用 laravel 访问器 get{Attribute}Attribute,您的代码应该可以正常工作,您也可以使用 @method 指令:

type User {
   #...
   name: String @method(name: "getName")
}

结帐: https://lighthouse-php.com/master/api-reference/directives.html#method & https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor