简体   繁体   中英

How to make related mutations in GraphQL?

How can we implement associated mutations in GraphQL?

I decided to make a portfolio for myself to study GraphQL and also to learn a new tool. I didn't have any difficulties until the moment when I needed to add an entry to my portfolio and images attached to it.

When you add an entry to a portfolio, it has related entities that are represented as additional images. They have a title, description, and multiple tags. The images, like the portfolio record itself, are in different tables and are linked by the ID of the portfolio record.

Here is where the question arises: how to add an entry with additional images in one mutation and link them, and how to do it correctly?

I searched the forums and clear manual I have not found. I have a couple of ideas on how to do this: use subscriptions or perform mutations through Promise. I suppose the first method is correct, but there are still doubts. Prompt how correctly to work with such mutations. Thank you for listening.

In development I use GraphQL, Apollo, Vue and Laravel.

Table structure:

CREATE TABLE IF NOT EXISTS `portfolio_works` (
  `id` int(10) unsigned NOT NULL,
  `portfolio_id` int(10) unsigned NOT NULL,
  `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `image` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` text COLLATE utf8mb4_unicode_ci,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `portfolio_work_images` (
  `id` int(10) unsigned NOT NULL,
  `portfolio_id` int(10) unsigned NOT NULL,
  `portfolio_work_id` int(10) unsigned NOT NULL,
  `image` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

I think you are overthinking things. Here is an approach:

type Portfolio {
    id: ID!
    portfolioImages: [PortfolioImages]
    title: String
    image: String
    description: String
}

type PortfolioImages {
    id: ID!
    portfolio: Portfolio
    image: String
    title: String
}

input PortfolioInput {
    id: ID!
    title: String!
    image: String!
    description: String
}

input PortfolioImagesInput {
    image: String
    title: String
}

extend type RootMutation {
    # Creates a new portfolio
    createPortfolio(item: PortfolioInput!, images: PortfolioImagesInput): Portfolio
}

Then inside your function that maps to the createPortfolio mutation you would create a MySQL transaction to create the necessary rows of data for your relationship and then COMMIT the transaction . Example of doing a transaction: https://github.com/mysqljs/mysql#transactions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM