【问题标题】:Laravel Lighthouse - How to update multiple modelsLaravel Lighthouse - 如何更新多个模型
【发布时间】:2020-08-19 19:46:51
【问题描述】:

我正在尝试使用指令更新多个模型,但当前的 @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
      }
   }
}

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

【问题讨论】:

  • 我之前没用过Lighthouse,请问可以正常查询吗?因为你可以做类似Model::whereIn('id', [6,8,10, ...])->update(['read' => true])
  • @DouwedeHaan 抱歉,问题不在于与 Laravel 相关的代码。我只是不知道如何使用自定义突变运行代码。
  • 你不认为在这种情况下你应该有一个接受数组的方法吗?如果它在一个记录上运行,那么它不会通过单独改变突变形状神奇地开始在集合上工作
  • @xadm 该方法正在为每个模型运行...
  • 什么?我不明白。

标签: php laravel graphql laravel-lighthouse


【解决方案1】:

找到了一种无需创建自定义指令的方法。刚刚使用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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2021-02-09
    相关资源
    最近更新 更多