Truy vấn dữ liệu PluginMeta Box
Meta Box
Các ví dụ về queries để tương tác với dữ liệu từ plugin Meta Box.
Lấy các trường tùy chỉnh của Meta Box
Chúng ta có thể sử dụng các trường meta để truy vấn dữ liệu trường tùy chỉnh của Meta Box, bất kể kiểu dữ liệu của chúng là gì:
query GetPost($postId: ID!) {
post(by: { id: $postId }) {
id
title
text: metaValue(key: "text_field")
textarea: metaValue(key: "textarea_field")
select: metaValue(key: "select_field")
multiSelect: metaValues(key: "multi_select_field")
}
}Nếu giá trị meta là một quan hệ (ví dụ: một bài viết, một người dùng, một taxonomy, v.v.), chúng ta có thể dùng giá trị đó để truy vấn thực thể tương ứng thuộc kiểu Post, User, Taxonomy, v.v.:
query GetPostWithRelationships($postId: ID!) {
post(by: { id: $postId }) {
id
title
# Xuất quan hệ tới một bài viết
relationshipPostId: metaValue(key: "relationship_post_id")
@export(as: "relationshipPostId")
# Xuất quan hệ tới một danh sách bài viết
relationshipPostIds: metaValues(key: "relationship_post_ids")
@export(as: "relationshipPostIds")
}
}
query QueryPostRelationships @depends(on: "GetPostWithRelationships") {
# Truy vấn quan hệ tới một bài viết
relationshipPost: post(by: { id: $relationshipPostId }) {
id
title
}
# Truy vấn quan hệ tới một danh sách bài viết
relationshipPosts: posts(filter: { ids: $relationshipPostIds }) {
id
title
}
}Cập nhật các trường tùy chỉnh của Meta Box
Chúng ta có thể sử dụng các mutation meta để cập nhật dữ liệu trường tùy chỉnh của Meta Box, bằng cách truyền tên trường và giá trị tương ứng, bất kể kiểu dữ liệu của chúng là gì:
mutation UpdatePost($postId: ID!) {
updatePost(
input: {
id: $postId
meta: {
text_field: ["New text value"],
textarea_field: ["New textarea value"],
select_field: ["New select value"],
multi_select_field: ["Choice 1", "Choice 2"],
}
}
) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
post {
id
text: metaValue(key: "text_field")
textarea: metaValue(key: "textarea_field")
select: metaValue(key: "select_field")
multiSelect: metaValues(key: "multi_select_field")
}
}
}Prev