i have schema:
input CreateProduct {
id_product: Int
content: CreateContentHasMany
manufacturer: CreateManufacturerHasOne
codes: ProductCodesInput
}
type Mutation {
createProduct(product: CreateProduct! @spread): Product @create
createProducts(products: [CreateProduct!]): [Product]! @create
}
我查询:
mutation {
createProducts(
products: [
{
content: {
create: [
{name: "some name"}
]
}
codes: {
reference: "AAA666"
}
}
]
){
id_product
}
}
创建单个产品作品,但是当我尝试创建产品列表时,我有错误:
Array to string conversion
.
我做错了什么?
@create
指令仅用于创建单个条目。
您可以创建一个自定义mutator来处理批量创建。
用artisan命令创建自定义mutator:php artisan lighthouse:mutation createProducts
由于mutator与mutator类具有相同的名称,它将自动被使用。
如果您创建了一个具有不同名称的it,您可以使用@field
指令来解析它。
input CreateProduct {
id_product: Int
content: CreateContentHasMany
manufacturer: CreateManufacturerHasOne
codes: ProductCodesInput
}
type Mutation {
createProduct(product: CreateProduct! @spread): Product @create
createProducts(products: [CreateProduct!]): [Product]!
}
此代码未经过测试,仅供参考!:)
<?php
namespace AppGraphQLMutations;
class CreateProducts
{
/**
* @param null $_
* @param array<string, mixed> $args
*/
public function __invoke($_, array $args)
{
// unsafe batch insert. Take care of relations!
return Product::insert($args['products']);
// loop and create
$products = [];
foreach ($args['products'] as $productData) {
// Create product. Take care of relations!
Product::create($productData);
// to
$product = new Product();
$product->fill($productData);
// do whatever before saving. E.g. solve and set relations
$product->save();
$products[] = $product;
}
return $products;
}
}