Craft CMS中如何在GraphQL条目突变中包含分类与资产?
Craft CMS GraphQL 条目突变:分类与资产字段处理
一、分类字段(creationProductType)处理
类型定义与参数传递
- 若为单选分类字段,变量类型设为
Int;若为多选分类字段,变量类型设为[Int](数组格式)。 - 直接传递分类ID的方式是正确的,只需传入分类对应的数值ID即可。
修正后的突变查询与变量(单选分类版本):
mutation SaveCreation($title: String, $slug: String, $creationProductType: Int, $creationImage: Int) { save_creations_creations_Entry( title: $title, slug: $slug, creationProductType: $creationProductType, creationImage: $creationImage ) { title slug creationProductType { id title } creationImage { title url } dateCreated @formatDateTime(format: "Y-m-d") } }
{ "title": "Supports GraphQL Mutations", "slug": "supports-mutations", "creationProductType": 8971, "creationImage": 1234 // 替换为目标资产的ID }
若为多选分类,调整变量类型与值即可:
mutation SaveCreation($title: String, $slug: String, $creationProductType: [Int], $creationImage: Int) { save_creations_creations_Entry( title: $title, slug: $slug, creationProductType: $creationProductType, creationImage: $creationImage ) { title slug creationProductType { id title } creationImage { title url } dateCreated @formatDateTime(format: "Y-m-d") } }
{ "title": "Supports GraphQL Mutations", "slug": "supports-mutations", "creationProductType": [8971, 8972], // 传入多个分类ID数组 "creationImage": 1234 }
二、资产字段(creationImage)处理
方式1:关联已有资产
直接传递目标资产的ID(数值类型)即可,前提是该资产已存在于Craft的资产卷中。
方式2:创建新资产并关联(嵌套突变)
如果需要在创建条目时同步创建资产,可使用嵌套的createAsset突变,需指定资产存入的卷ID:
mutation SaveCreationWithAsset($title: String, $slug: String, $creationProductType: Int, $assetTitle: String, $assetUrl: String, $volumeId: Int) { save_creations_creations_Entry( title: $title, slug: $slug, creationProductType: $creationProductType, creationImage: { create: { title: $assetTitle, url: $assetUrl, volumeId: $volumeId } } ) { title slug creationProductType { id title } creationImage { title url } dateCreated @formatDateTime(format: "Y-m-d") } }
{ "title": "Supports GraphQL Mutations", "slug": "supports-mutations", "creationProductType": 8971, "assetTitle": "practice image", "assetUrl": "https://imgur.com/123asfgfgfdg", "volumeId": 567 // 替换为你的资产卷ID }
注意事项
- 确保GraphQL模式已开启条目突变权限,且
creationProductType、creationImage字段已在GraphQL设置中对外暴露。 - 嵌套创建资产时,
volumeId为必填项,需对应目标资产卷的ID。 - 查询返回字段时,建议展开分类与资产的子字段(如
id、title),便于验证关联是否成功。
内容的提问来源于stack exchange,提问作者Alyssa Jackson
相关产品推荐
相关产品推荐

