1

我一直在尝试将我的旧 API 迁移到 GraphQl,我试图只加载一次,但是使用 graphql lighthouse 我找不到正确的方法

我的模型

public function getMeta($name, $defaultValue = null)
{
    if (!$this->relationLoaded('metas')) {
        return $defaultValue;
    }

    return $this->metas->where('name', $name)->first()->value ?? $defaultValue;
}

以前我一直在使用 laravel jsonResources

'built_year' => $this->getMeta('built_year'),
            'floors' => $this->getMeta('floors'),
            'cabins' => $this->getMeta('cabins'),

使用这个有一个对元表的请求

但现在使用 graphql 它正在使每个数据库请求与每次$this->getMeta调用我的模式

type Cruise{
built_year : GetMeta @field(resolver:"App\\GraphQL\\Types\\GetMetaTypes@get")
    floors : GetMeta @field(resolver:"App\\GraphQL\\Types\\GetMetaTypes@get")
    cabins : GetMeta @field(resolver:"App\\GraphQL\\Types\\GetMetaTypes@get")
}

type GetMeta{
    value : String
}

自定义类型

public function get($cruise,$next,$a,$b)
    {
        $cruise->load("metas");
        return ['value' => $cruise->getMeta($b->fieldName) ];
    }
4

1 回答 1

2

在您的最后一种方法中,您每次都重新加载关系:$cruise->load("metas"). 你应该做的是只加载一次关系。你可以用$cruise->loadMissing('metas'). 尽可能使用单引号。

于 2020-02-02T18:24:57.003 回答