首先composer安装扩展包:folklore/graphql(github-most stars),然后最好是不管laravel哪个版本先去config\app.php添加个provider,即添加这样一句:
Folklore\GraphQL\ServiceProvider::class,
然后再去publish配置
php artisan vendor:publish --provider="Folklore\GraphQL\ServiceProvider"
因为理论上laravel5.5以上版本会自动搞定,但是我之前没添加provider就publish不完全。
Publish后就能在config\下看到多了一个graphql.php文件,这个配置文件不像其他的一次性就能修改好,而是根据项目需要所产生的Query和Type都需要在里面“备案”一下,所以需要经常修改,下面会讲到。
接下来开始写接口,首先要写Type设置以某种格式(int,string等内置或根据需要自设)返回某个model的哪些字段,个人理解这里的Type类似于DingoAPI的Transformer的作用,具体自行了解。
以活动和门票举例,活动与门票为一对多关系,在Activity和Ticket的model里当然要有相应的关联方法,而且方法命名要合乎逻辑才行,比如这里:
Activity.php:
Ticket.php:
下面直接上ActivityType和TicketType的代码,直接在代码里注释了
ActivityType.php
<?php
/**
* Created by Lilei.
* Date: 2018/11/14
* Time: 13:40
* Introduction:
*/
namespace App\GraphQL\Type;
use App\Models\Activity;
use Folklore\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Type as GraphQLType;
class ActivityType extends GraphQLType
{
protected $attributes = [
'name' => 'activity', // 该处设置要准确有意义,配置文件中备案时要用到
'description' => '活动',
'model' => Activity::class
];
/**
* 定义返回的字段接口,即可以通过你写的接口获取到该model哪些字段
* @return array
*/
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::int()), // nonNull是不能为空的意思,即该字段值为空时会查询失败
'description' => '活动id'
],
'title' => [
'type' => Type::string(),
'description' => '活动主题'
],
'description' => [
'type' => Type::string(),
'description' => '活动简介'
],
'address' => [
'type' => Type::string(),
'description' => '活动举办地址'
],
'holding_on' => [
'type' => Type::string(),
'description' => '活动举办时间'
],
'started_at' => [
'type' => Type::string(),
'description' => '活动报名开始时间'
],
'ended_at' => [
'type' => Type::string(),
'description' => '活动报名结束时间'
],
'created_at' => [
'type' => Type::string(),
'description' => '创建时间'
],
'updated_at' => [
'type' => Type::string(),
'description' => '更新时间'
],
'tickets' => [
'type' => Type::listOf(GraphQL::type('ticket')), // 此处即是一对多的关联设置,listOf方法返回关联的所有数据
'description' => '活动的门票类型'
]
];
}
// 因为laravel自动保存的创建、更新、软删除时间字段为Carbon对象,而上面只能设置
//返回字符串,所以要在下面对不符合指定类型的字段
// 手动做一下处理,方法的命名严格按照下面格式来
/**
* @description 单独处理created_at字段为string格式
*
* @author Lilei
*/
protected function resolveCreatedAtField($root, $args)
{
return $root->created_at . '';
}
/**
* @description 单独处理updated_at字段为string格式
*
* @au