灯塔渴望加载关系

时间:2020-02-02 17:49:32

标签: laravel graphql laravel-lighthouse

我一直在尝试将旧的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'),

使用此功能,对metas表发出一个请求

,但是现在使用graphql,它使每个db req每次调用$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) ];
    }

1 个答案:

答案 0 :(得分:2)

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

相关问题