在Laravel + Lighthouse的GraphQL服务器中添加新模式的步骤
GraphQL真是方便啊!我希望能够更多地进行设计。
我正在使用Laravel和Lighthouse进行实现,并整理了添加新模式的步骤。
我們已經添加了許多模式,但基本上它們與表格 === 模型 === 模式相對應。
通過這樣做,我們能夠維持實施的一致性,並能夠快速進行模式的添加。
下面將總結這個過程的步驟。
在Sail环境中,请将php替换为sail。
1. 服务器端 (Server-side)
-
- 模型+迁移创建
-
- 电子表格
- 播种机
1.1. 创建模型和迁移。
$ php artisan make:model Post -m
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
if ( Schema::hasTable( env( 'DB_TABLE_PREFIX' ) . 'banks' ) ) {
return;
}
Schema::create('posts', function ( Blueprint $table ) {
$table->id()->comment( 'ID' );
$table->string( 'code' )->nullable()->comment( '検索用コード' );
$table->string( 'name' )->nullable()->comment( 'ポスト名' );
$table->timestamps();
$table->softDeletes( 'deleted_at' )->comment( '削除日時' );
});
DB::statement( "ALTER TABLE banks comment 'ポスト'" );
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::disableForeignKeyConstraints();
Schema::dropIfExists( 'posts' );
Schema::enableForeignKeyConstraints();
}
}
1.2. 电子表格
我将在Google表格上创建测试数据。

使用 GSS API 将测试数据转换为 JSON 格式。

[
{
"ID": "1",
"code": "1",
"name": "投稿タイトル1",
"created": "2021-11-05 06:09:51",
"modified": "2021-11-05 06:09:51"
},
...
1.3. 种子机
创建一个种子类并进行读取操作。
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class BankSeeder extends Seeder {
/**
* Run the database seeds.
*
* @return void
*/
public function run() {
\App\Models\Post::factory( 10 )->create();
}
}
如果能够做到这一步,就进行迁移等操作并进行试验。
2. GraphQL(灯塔)
我将创建一个服务器端的GraphQL。
-
- 架构
-
- 查询
- 变更
2.1. 模式
"投稿"
type Post {
id: ID!
"コード"
code: String
"投稿タイトル"
name: String
"非表示"
invisible: Boolean
}
2.2. 查询
我将写下查询。
extend type Query @guard {
"投稿一覧取得"
Posts: [Post!]! @paginate(type: CONNECTION)
"投稿取得"
Post(id: Int! @eq): Post @find
}
2.3. 变异
写下突变。
extend type Mutation @guard {
"投稿入力"
mutationPost(input: InputDailyDrivingReport @spread): Post @upsert
}
input InputPost {
"ID"
id: ID
"コード"
code: String
"投稿タイトル"
name: String
}
以上的伺服器端實現已完成。