0

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

所以 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
      }
   }
}

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

4

1 回答 1

4

找到了一种无需创建自定义指令的方法。刚刚用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
  }
}
于 2020-05-06T13:01:34.890 回答