My products
and tags
models have a many to many relationship through the productTags
model.
product Model
Products.belongsToMany(models.tags, {
through: 'productTags',
foreignKey: 'product_id',
otherKey: 'tags_id',
as: 'tags',
});
tags Model
Tags.belongsToMany(models.products, {
through: 'productTags',
foreignKey: 'tags_id',
otherKey: 'product_id',
as: 'products',
});
productTags Model
ProductTags.belongsTo(models.products, {
foreignKey: {
name: 'productIdKey',
field: 'product_id',
},
as: 'product',
});
ProductTags.belongsTo(models.tags, {
foreignKey: {
name: 'tagsIdKey',
field: 'tags_id',
},
as: 'tags',
});
Expected behavior
When I create a Smart Field from a many to many relationship, I can in turn edit associations from the Edit record interface.
Actual behavior
The following code defines my Smart Fields in the /forest/products.js
file
const tagTypeFields = getTagTypeFields()
collection('products', {
actions: [],
fields: [...tagTypeFields],
segments: [],
});
function getTagTypeFields() {
const tagTypes = getTagTypes()
return tagTypes.map(tagType => {
let tagTypeName = produtTagsMap[tagType]
return {
field: tagTypeName,
type: 'String',
get: (product) => displayTagName(product, tagType),
set: async (product, tagName) => {
const productBeforeUpdate = await models.products.findOne({ where: { id: product.id }});
const updatedTag = await models.tags.findOne({ where: { name: tagName }});
await productBeforeUpdate.addTag(updatedTag)
return product
}
}
})
}
Failure Logs
The line which runs await productBeforeUpdate.addTag(updatedTag)
Executes the following SQL statement and immediately throws an error:
Executing (default): SELECT "product_id" AS "productId", "tags_id" AS "tagsId", "product_id" AS "productIdKey", "tags_id" AS "tagsIdKey", "product_id", "tags_id" FROM "public"."product_tags" AS "productTags" WHERE "productTags"."product_id" = '607' AND "productTags"."tags_id" IN ('145');
Unhandled rejection
AggregateError of:
SequelizeBulkRecordError: notNull Violation: productTags.productId cannot be null,
notNull Violation: productTags.tagsId cannot be null
Context
This is my package.json
{
"name": "foxxbee-admin",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./server.js"
},
"dependencies": {
"body-parser": "1.19.0",
"chalk": "~1.1.3",
"cookie-parser": "1.4.4",
"cors": "2.8.5",
"debug": "~4.0.1",
"dotenv": "~6.1.0",
"express": "~4.17.1",
"express-jwt": "6.0.0",
"forest-cli": "^2.3.5",
"forest-express-sequelize": "^8.0.0",
"morgan": "1.9.1",
"pg": "~8.2.2",
"require-all": "^3.0.0",
"sequelize": "~5.15.1"
}
}