Laravel Lighthouse - 如何更新多个模型

Laravel Lighthouse - How to update multiple models

我正在尝试使用指令更新多个模型,但当前的@update 指令不支持多个 ID。我基本上想要 @delete 指令(您可以在其中使用 ID 列表)。更新多个模型。我猜我可以创建一个自定义指令,但是那里有很多代码,我无法理解。我试图阅读 docs 以了解如何创建自定义指令,但我无法让它工作。

所以 DeleteDirective.php 得到了这个:

/**
 * Bring a model in or out of existence.
 *
 * @param \Illuminate\Database\Eloquent\Model $model
 * @return void
 */
protected function modifyExistence(Model $model): void
{
    $model->delete();
}

我基本上想要这个(对于多个 ID):

    /**
    * Update a model to read true
    *
    * @param \Illuminate\Database\Eloquent\Model $model
    * @return void
    */
protected function updateRead(Model $model): void
{
    $model->update(['read' => true]);
}

通过像这样定义一个变异查询:

type Mutation {
  updatePostsToRead(id: [ID!]!): [Post!]! @updateRead
}

并进行如下查询:

{
   mutation {
      updatePostsToRead(id: [6,8]) {
         id
         amount
      }
   }
}

有谁知道我这样做会怎样?或者可以指出正确的方向吗?

找到了一种无需创建自定义指令即可实现的方法。刚刚使用 php artisan lighthouse:mutation updatePostsToRead.

进行了自定义突变

updatePostsToRead.php:

class updatePostsToRead
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke(
        $rootValue,
        array $args,
        GraphQLContext $context,
        ResolveInfo $resolveInfo
    ) {
        // TODO implement the resolver
        \DB::table('posts')
            ->whereIn('id', $args["ids"])
            ->update(['read' => true]);

        $posts = Post::whereIn('id', $args["ids"])->get();

        return $posts;
    }
}

架构:

type Mutation {
    updatePostsToRead(ids: [ID]): [Post]
}

客户端查询:

mutation{
  updatePostsToRead(ids: [2,6,8]) {
    id
    description
    read
  }
}