Để tạo nhiều bản ghi một lúc trong Strapi ta sẽ dùng method createMany() của Query engine API. Nhưng nếu bản ghi đó có foreign key(khoá ngoại) liên kết đến thì không thể dùng method trên vì vấn đề hiệu suất. Lúc này chúng ta sẽ sử dụng Entity service kết hợp Promise.all().
Trong bài viết này chúng ta sẽ tạo hàng loạt link ảnh, và mỗi link ảnh thuộc về 1 category (chính là khoá ngoại).
Controller cho API như sau:
'use strict';
/**
* image-album controller
*/
const _ = require('lodash');
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::image-album.image-album', ({ strapi }) => ({
async createMultiImageAlbums(ctx) {
try {
let promiseArr = [];
// @ts-ignore
_.forEach(ctx.request.body, item => {
promiseArr.push(this.createImageAlbums(item))
})
let allImagePromise = await Promise.all(promiseArr);
ctx.send({
status: 200,
data: allImagePromise
})
} catch (error) {
return ctx.badRequest("Tạo mới không thành công!")
}
},
}));
Trong đó, method createImageAlbums là 1 promise thực hiện việc tạo từng bản ghi link ảnh trong mảng truyền vào.
Method createImageAlbums:
'use strict';
/**
* image-album controller
*/
const _ = require('lodash');
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::image-album.image-album', ({ strapi }) => ({
async createImageAlbums(image) {
return new Promise(async (resolve, reject) => {
let res = await strapi.entityService.create('api::image-album.image-album', {
data: {
...image,
categoryId: {
// @ts-ignore
set: [image.categoryId]
}
}
});
resolve(res)
});
},
async createMultiImageAlbums(ctx) {},
}));
Trong đó, set dùng để gán categoryId đến mỗi bản ghi link ảnh.