0

I am building a plant/arboretum style application in JavaScript. I am trying to create a one-to-many relationship between Supplier model and TreeSeed model. Meaning that one supplier can sell multiple tree seed types.

I have looked at the sequelize documentation and it seems you use hasMany() and belongsTo() along with their options plus model.bulkCreate if you want to insert multiple records.

I want seedcompany_id in the TreeSeed model to reference supplier_id in the Supplier model and then I use bulkCreate to insert my data. I have tried multiple combinations but it will not let me insert the records. I can only get as far as creating the models.

The data I want to insert are two arrays(arrays of objects) (treeSeedData and suppliersData). I can connect to the database fine.

//tree_seeds.js file

const {DataTypes, Model} = require("sequelize");

const sequelize = require("../config/sequelize.js")

const treeSeedData = [
    {
      common_name:"Common Hazel/Cob-Nut",
      species_name:"Corylus avellana",
      family:"Betulaceae",
      seed_cost_incl_VAT:2.18,
      quantity_in_stock:14,
      seed_number_per_pack:8,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam",
      soil_acidity:"alkaline/neutral",
      description:"A small shrubby tree found in mixed woodlands and hedgerows known for its long yellow catkins that appear in Spring and then produces hazelnuts in Summer. It is native to the UK.",
      tree_image1:`${__dirname}/tree_photos/hazel1.png`,
      tree_image2:`${__dirname}/tree_photos/hazel2.jng`,
      tree_image3:`${__dirname}/tree_photos/hazel3.jng`,
      seedcompany_name:"Gracey Seed-Co Ltd" 
      //image(s) collected
    },
    {
      common_name:"Common Alder",
      species_name:"Alnus glutinosa",
      family:"Betulaceae",
      seed_cost_incl_VAT:3.22,
      quantity_in_stock:10,
      seed_number_per_pack:234,
      colour:"green",
      hardiness:"hardy",
      soil_type:"clay/chalk/loam",
      soil_acidity:"alkaline/neutral/acid",
      description:"Common in wetland forests, fens and riversides. It can improve soil fertility with its ability to fix nitrogen. Used to make timber veneers, pulp and plywood.",
      tree_image1:`${__dirname}/tree_photos/alnus_glutinosa1.jpg`,
      tree_image2:`${__dirname}/tree_photos/alnus_glutinosa2.jpg`,
      tree_image3: null,
      seedcompany_name:"Gracey Seed-Co Ltd" 
       //image(s) collected
    },
    {
      common_name:"Silver Birch",
      species_name:"Betula pendula",
      family:"Betulaceae",
      seed_cost_incl_VAT:2.75,
      quantity_in_stock:6,
      seed_number_per_pack:1680,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"It is native to Northern Europe and is found on light and dry soils. Woodpeackers commonly nest in the trunks of this tree. It is a hardwood used in plywood production, toys and wooden back of brushes.",
      tree_image1:`${__dirname}/tree_photos/betula_pendula1.jpg`,
      tree_image2:`${__dirname}/tree_photos/betula_pendula2.jpg`,
      tree_image3:`${__dirname}/tree_photos/betula_pendula3.jpg`,
      seedcompany_name:"Fothergill Seeds Ltd"
      //image(s) collected
    },
    {
      common_name:"Cherry Dogwood/Cornelian Cherry",
      species_name:"Cornus mas",
      family:"Cornaceae",
      seed_cost_incl_VAT:3.20,
      quantity_in_stock:7,
      seed_number_per_pack:19,
      colour:"yellow/orange",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"It is a multi-stemmed shrub/tree that is notable for being disease-resistant. The fruit produced has skin that is unpleasant with a grainy and bitter taste. They are native to North America, Asia and Europe. It is strong and sturdy and these properties make it a good building material.",
      tree_image1:`${__dirname}/tree_photos/cornus_mas1.jpg`,
      tree_image2:`${__dirname}/tree_photos/cornus_mas2.jpg`,
      tree_image3:`${__dirname}/tree_photos/cornus_mas3.jpg`,
      seedcompany_name:"Chiltern Seeds"
      //image(s) collected
    },
    {
      common_name:"Sugar Maple",
      species_name:"Acer sacchurum",
      family:"Aceraceae",
      seed_cost_incl_VAT:2.99,
      quantity_in_stock:20,
      seed_number_per_pack:18,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"The leaf of the tree is the national emblem of Canada; known for producing a sweet maple syrup and is native to eastern North America. Leaves have three to five lobes and show various shades of gold to scarlet in autumn. It produces greenish yellow flowers in Spring.",
      tree_image1:`${__dirname}/tree_photos/acer_saccharum1.jpg`,
      tree_image2:`${__dirname}/tree_photos/acer_saccharum2.jpg`,
      tree_image3: null,
      seedcompany_name:"D.T. Brown Seeds"
      //image(s) collected
    },
    {
      common_name:"Black Mulberry",
      species_name:"Morus nigra",
      family:"Moraceae",
      seed_cost_incl_VAT:2.65,
      quantity_in_stock:20,
      seed_number_per_pack:288,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"A species native to west Asia that is cultivated for its fruit. It produces dark-green heart shaped leaves and is deciduous. It is low maintenance, attracts pollinators and improves soil health.",
      tree_image1: `${__dirname}/tree_photos/morus_nigra1.jpg`,
      tree_image2: `${__dirname}/tree_photos/morus_nigra2.jpg`,
      tree_image3: `${__dirname}/tree_photos/morus_nigra3.jpg`,
      seedcompany_name:"D.T. Brown Seeds"
      //image(s) collected
    },
    {
      common_name:"Lemonade Tree/Baobob",
      species_name:"Adansonia digitata",
      family:"Bombacaceae",
      seed_cost_incl_VAT:3.10,
      quantity_in_stock:15,
      seed_number_per_pack:6,
      colour:"green",
      hardiness:"tender",
      soil_type:"sand/loam",
      soil_acidity:"alkaline/neutral/acid",
      description:"This tree produces short stubby branches from the top of a swollen water-containing trunk. They grow in 32 African countries and can live up to 5000 years. Its pendulous flowers are pollinated by bush babies and bats, its young leaves are edible and produces a woody fruit.",
      tree_image1:`${__dirname}/tree_photos/boabab1.jpg`,
      tree_image2:`${__dirname}/tree_photos/boabab2.jpg`,
      tree_image3:null,
      seedcompany_name:"Chiltern Seeds" 
      //image(s) collected
    },
    {
      common_name:"Common Hornbeam",
      species_name:"Carpinus betulus",
      family:"Betulaceae",
      seed_cost_incl_VAT:2.85,
      quantity_in_stock:20,
      seed_number_per_pack:27,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"Found in southern and easter England; it produces catkins in late Spring and winged seeds can be spotted in autumn and are dispersed by the wind.It has a twisted trunk with tooth-edged leaves. Commonly it is used for flooring and furniture.",
      tree_image1:`${__dirname}/tree_photos/carpinus_betulus1.jpg`,
      tree_image2:`${__dirname}/tree_photos/carpinus_betulus_catkins2.jpg`,
      tree_image3:null,
      seedcompany_name:"Chiltern Seeds" 
      //image(s) collected
    },
    {
      common_name:"Argyle Apple/Mealy Stringybark",
      species_name:"Eucalyptus cinerea",
      family:"Myrtaceae",
      seed_cost_incl_VAT:2.90,
      quantity_in_stock:16,
      seed_number_per_pack:26,
      colour:"greyish-white",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"neutral/acid",
      description:"This is an evergreen tree with a striking canopy of blue-silver foliage. It is tolerant to UK climate, prefers slightly acidic soil and is used as an astringent and antiseptic.",
      tree_image1:`${__dirname}/tree_photos/eucalyptus_cinerea1.jpg`,
      tree_image2:`${__dirname}/tree_photos/eucalyptus_cinerea2.jpg`,
      tree_image3:null,
      seedcompany_name:"Kings Seeds"
      //image(s) collected
    },
    {
      common_name:"Dawn Redwood",
      species_name:"Metasequoia glyptostroboides",
      family:"Pinaceae",
      seed_cost_incl_VAT:3.30,
      quantity_in_stock:13,
      seed_number_per_pack:70,
      colour:"mixed",
      hardiness:"hardy",
      soil_type:"chalk/sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"A native tree of China but grows comfortably in UK climates. Mostly planted as an ornamental tree and is a fast growing deciduous tree with needle-like green leaves that turn copper-red when shed in autumn.",
      tree_image1:`${__dirname}/tree_photos/dawn_redwood1.jpg`,
      tree_image2:`${__dirname}/tree_photos/dawn_redwood2.jpg`,
      tree_image3:`${__dirname}/tree_photos/dawn_redwood3.jpg`,
      seedcompany_name:"D.T. Brown Seeds" 
      //image(s) collected
    },
    {
      common_name:"Norway Maple",
      species_name:"Acer platanoides",
      family:"Aceraceae",
      seed_cost_incl_VAT:1.92,
      quantity_in_stock:10,
      seed_number_per_pack:20,
      colour:"yellow/orange",
      hardiness:"hardy",
      soil_type:"sand/loam/clay",
      soil_acidity:"alkaline/neutral/acid",
      description:"This tree is found expansively across Europe and Asia and is a common ornamental landscape plant. When they grow they produce a lot of shade that makes it hard for plants and grass underneath to grow.",
      tree_image1:`${__dirname}/tree_photos/acer_platanoides1.jpg`,
      tree_image2:`${__dirname}/tree_photos/acer_platanoides2.jpg`,
      tree_image3:`${__dirname}/tree_photos/acer_platanoides3.jpg`,
      seedcompany_name:"Moles Seeds Ltd"
    },
    {
      common_name:"Cootamundra Wattle",
      species_name:"Acacia baileyana",
      family:"Leguminosae/Fabaceae",
      seed_cost_incl_VAT:1.34,
      quantity_in_stock:26,
      seed_number_per_pack:24,
      colour:"yellow",
      hardiness:"hardy/half-hardy",
      soil_type:"sand/loam",
      soil_acidity:"neutral/acid",
      description:"This is a tree/shrub with smooth grey-to-brown bark and blue-grey foliage. It is planted in parks and gardens as a wind-break and shading tree.",
      tree_image1:`${__dirname}/tree_photos/acacia_baileyana1.jpg`,
      tree_image2:`${__dirname}/tree_photos/acacia_baileyana2.jpg`,
      tree_image3: null,
      seedcompany_name:"Moles Seeds Ltd"
      //image(s) collected
    },
  ];

class TreeSeed extends Model {
  
    
}
TreeSeed.init({
    
    seed_id:{
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoincrement: true,
        allowNull:false
    },
    common_name:{
        type: DataTypes.STRING(45),
        unique: true,
        allowNull: false
    },
    species_name:{
        type: DataTypes.STRING(45),
        unique:true,
        allowNull: false
    },
    family:{
        type: DataTypes.STRING(45),
        allowNull: false
    },
    seed_cost_incl_VAT:{
        type: DataTypes.DOUBLE(4,2),
        allowNull: false
    },
    quantity_in_stock:{
        type: DataTypes.INTEGER,
        allowNull: false
    },
    seed_number_per_pack:{
        type: DataTypes.INTEGER,
        allowNull: false
    },
    colour:{
        type: DataTypes.STRING(20),
        allowNull: false
    },
    hardiness:{
        type: DataTypes.STRING(20),
        allowNull: false
    },
    soil_type:{
        type: DataTypes.STRING(60),
        allowNull: false
    },
    soil_acidity:{
        type: DataTypes.STRING(60),
        allowNull: false
    },
    description:{
        type: DataTypes.TEXT,
        allowNull: false
    },
    tree_image1:{
        type: DataTypes.BLOB,
        allowNull: false
    },
    tree_image2:{
        type: DataTypes.BLOB,
        
    },
    tree_image3:{
        type: DataTypes.BLOB,       
    },
    seedcompany_id:{
        type: DataTypes.INTEGER,
        references:{
           model: 'Supplier',
           key: 'supplier_id'
        }
    }
    }

    ,{
     sequelize,
     timestamps: false,
     freezeTableName: true

})
 

module.exports = {TreeSeed,treeSeedData};

//index.js
const {TreeSeed,treeSeedData} = require("./tree_seeds.js")
const {Supplier,suppliersData} = require("./supplier.js");
const { Model } = require("sequelize");


Supplier.hasMany(TreeSeed,{
    foreignKey: 'seedcompany_id'
});
TreeSeed.belongsTo(Supplier,{
    foreignKey: 'seedcompany_id'
})
module.exports = {TreeSeed,treeSeedData,Supplier,suppliersData};
//supplier.js

const {DataTypes, Model} = require("sequelize");
const sequelize = require("../config/sequelize.js")

const suppliersData = [
    {
      supplier_name: "Kent & Stowe" //1
    },
    {
      supplier_name: "Spear & Jackson" //2
    },
    {
      supplier_name: "Wilkinson Sword" //3
    },
    {
      supplier_name: "Darlac Ltd" //4
    },
    {
      supplier_name: "Walensee" //5
    },
    {
      supplier_name: "Evergreen Garden Care Ltd" //6
    },
    {
      supplier_name: "Neilsen" //7
    },
    {
      supplier_name: "Flymo" //8
    },
    {
      supplier_name: "Burgon & Ball" //9
    },
    {
      supplier_name: "Colwelt" //10
    },
    {
      supplier_name: "Alina" //11
    },
    {
      supplier_name: "GreFusion" //12
    },
    {
      supplier_name: "GardenGloss" //13
    },
    {
      supplier_name: "Nutscene" //14
    },
    {
      supplier_name: "Gracey Seed-Co Ltd" //15
    },
    {
      supplier_name: "Fothergill Seeds Ltd" //16
    },
    {
      supplier_name: "Chiltern Seeds" //17
    },
    {
      supplier_name: "D.T. Brown Seeds" //18
    },
    {
      supplier_name: "Kings Seeds" //19
    },
    {
      supplier_name: "Moles Seeds Ltd" //20
    },
    {
      supplier_name: "Miracle Gro" //21
    },
    {
      supplier_name: "Jamieson Brothers" //22
    },
    {
      supplier_name: "Tree Appeal" //23
    },
    {
      supplier_name: "Noel Tatt" //24
    },
    {
      supplier_name: "DV Design" //25
    },
    {
      supplier_name: "Woodmansterne" //26
    },
    {
      supplier_name: "Abacus Cards" //27
    },
    {
      supplier_name: "Nokular Limited" //28
    },
    {
      supplier_name: "Purple Fox" //29
    },
  
  ]

class Supplier extends Model {
  
}

Supplier.init({
    supplier_id:{
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoincrement: true
    },
    supplier_name:{
        type: DataTypes.STRING(60),
        allowNull: false
    },
},{
    sequelize,
    timestamps: false,
    freezeTableName: true,

})

module.exports =  {Supplier,suppliersData};
   //utility_funcs/utilities.js


function createSupplierRef(suppliersData){//for orders
    const supplierLookup = {}
    const supplierDataCopy = [...suppliersData]
   const creationLookup = supplierDataCopy.map((supplier)=>{
      const supplierCpy = {...supplier}
     supplierLookup[supplierCpy.supplier_name] = supplierCpy.supplier_id
    })

    //{fothergill : 14}
    return supplierLookup
}

function addSupplierIdToSeeds(treeSeedData,supplierLookup){//switch out shape in bird_orders
    const newSeedArray = treeSeedData.map((seed)=>{
      const seedCpy = {...seed}
      seedCpy.seedcompany_id = supplierLookup[seedCpy.seedcompany_name]
      delete seedCpy.seedcompany_name
      return seedCpy
    })
    return newSeedArray
  }

  module.exports = {createSupplierRef,addSupplierIdToSeeds}


//server.js

const sequelize = require("./config/sequelize.js")
const {TreeSeed,Supplier,treeSeedData,suppliersData} = require("./models")
const {createSupplierRef,addSupplierIdToSeeds} = require("./utility_funcs/utilities.js")

const authenticate = async () => {
   try{
      await sequelize.authenticate();
      console.log("authentication successful")
   }catch(error){
      console.error('Unable to connect to the database:',error)
   }
}
authenticate();
const makeModels = async () => {
   try{
      await sequelize.sync({force:true});
      console.log("All models made")
   }catch(error){
      console.error('Unable to connect to make tables:',error)
   }
};
makeModels();

const insertSupplier = async () =>{
   try{
      const arrayLen = suppliersData.length
      let supplier;
      let binArr = [];
      for(let i=0; i < arrayLen; i++){
        supplier = await Supplier.create(suppliersData[i])
        binArr = [...supplier.dataValues]
      }
    console.log("Suppliers data successfully inserted")
    return binArr;
   }catch(error){
      console.error("Could not insert supplier records:",error)
      return [];

   }
};


const insertTreeSeed = async (suppliers) =>{
   try{
      //swap out logic
      const supplierRefObj = createSupplierRef(suppliers)
      const newTreeSeedData = addSupplierIdToSeeds(treeSeedData,supplierRefObj)
      const arrayLen = newTreeSeedData.length
      let treeSeed;
      for(let i=0; i < arrayLen; i++){
        treeSeed = await TreeSeed.create(suppliersData[i])
      }
       console.log("Treeseed data successfully inserted")
   
   }catch(error){
      console.error("Could not insert tree seed records:",error)
   }
}
insertSupplier().then((suppliers)=>insertTreeSeed(suppliers))

In terms of the what appears in terminal after I have done

npm run mysql -u username -p

and then follow up with node server.js I get the following in the terminal:

//Error in the terminal when node server.js is ran

//The catch block in insertSuppplier creates the ER_NO_SUCH_TABLE error that then causes //the null violation errors in insertTreeSeed from what it looks like

Could not insert supplier records: Error
   
      at Socket.emit (node:events:514:28)
      at addChunk (node:internal/streams/readable:343:12)
      at readableAddChunk (node:internal/streams/readable:316:9)
      at Readable.push (node:internal/streams/readable:253:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'items_dev_db.Supplier' doesn't exist",
    sql: 'INSERT INTO `Supplier` (`supplier_name`) VALUES (?);',
    parameters: [ 'Kent & Stowe' ]
  },
  original: Error: Table 'items_dev_db.Supplier' doesn't exist
      at Packet.asError 
      at Socket.emit (node:events:514:28)
      at addChunk (node:internal/streams/readable:343:12)
      at readableAddChunk (node:internal/streams/readable:316:9)
      at Readable.push (node:internal/streams/readable:253:10) {
    code: 'ER_NO_SUCH_TABLE',
    errno: 1146,
    sqlState: '42S02',
    sqlMessage: "Table 'items_dev_db.Supplier' doesn't exist",
    sql: 'INSERT INTO `Supplier` (`supplier_name`) VALUES (?);',
    parameters: [ 'Kent & Stowe' ]
  },
  sql: 'INSERT INTO `Supplier` (`supplier_name`) VALUES (?);',
  parameters: [ 'Kent & Stowe' ]
}
Could not insert tree seed records: ValidationError [SequelizeValidationError]: notNull Violation: TreeSeed.common_name cannot be null,
notNull Violation: TreeSeed.species_name cannot be null,
notNull Violation: TreeSeed.family cannot be null,
notNull Violation: TreeSeed.seed_cost_incl_VAT cannot be null,
notNull Violation: TreeSeed.quantity_in_stock cannot be null,
notNull Violation: TreeSeed.seed_number_per_pack cannot be null,
notNull Violation: TreeSeed.colour cannot be null,
notNull Violation: TreeSeed.hardiness cannot be null,
notNull Violation: TreeSeed.soil_type cannot be null,
notNull Violation: TreeSeed.soil_acidity cannot be null,
notNull Violation: TreeSeed.description cannot be null,
notNull Violation: TreeSeed.tree_image1 cannot be null{
  errors: [
    ValidationErrorItem {
      message: 'TreeSeed.common_name cannot be null',
      type: 'notNull Violation',
      path: 'common_name',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.species_name cannot be null',
      type: 'notNull Violation',
      path: 'species_name',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.family cannot be null',
      type: 'notNull Violation',
      path: 'family',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.seed_cost_incl_VAT cannot be null',
      type: 'notNull Violation',
      path: 'seed_cost_incl_VAT',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.quantity_in_stock cannot be null',
      type: 'notNull Violation',
      path: 'quantity_in_stock',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.seed_number_per_pack cannot be null',
      type: 'notNull Violation',
      path: 'seed_number_per_pack',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.colour cannot be null',
      type: 'notNull Violation',
      path: 'colour',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.hardiness cannot be null',
      type: 'notNull Violation',
      path: 'hardiness',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.soil_type cannot be null',
      type: 'notNull Violation',
      path: 'soil_type',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.soil_acidity cannot be null',
      type: 'notNull Violation',
      path: 'soil_acidity',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.description cannot be null',
      type: 'notNull Violation',
      path: 'description',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    },
    ValidationErrorItem {
      message: 'TreeSeed.tree_image1 cannot be null',
      type: 'notNull Violation',
      path: 'tree_image1',
      value: null,
      origin: 'CORE',
      instance: [TreeSeed],
      validatorKey: 'is_null',
      validatorName: null,
      validatorArgs: []
    }
  ]
}

Executing (default): SELECT CONSTRAINT_NAME as constraint_name,CONSTRAINT_NAME as constraintName,CONSTRAINT_SCHEMA as constraintSchema,CONSTRAINT_SCHEMA as constraintCatalog,TABLE_NAME as tableName,TABLE_SCHEMA as tableSchema,TABLE_SCHEMA as tableCatalog,COLUMN_NAME as columnName,REFERENCED_TABLE_SCHEMA as referencedTableSchema,REFERENCED_TABLE_SCHEMA as referencedTableCatalog,REFERENCED_TABLE_NAME as referencedTableName,REFERENCED_COLUMN_NAME as referencedColumnName FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = 'Supplier' AND CONSTRAINT_NAME!='PRIMARY' AND CONSTRAINT_SCHEMA='items_dev_db' AND REFERENCED_TABLE_NAME IS NOT NULL;
Executing (default): DROP TABLE IF EXISTS `TreeSeed`;
Executing (default): DROP TABLE IF EXISTS `Supplier`;
Executing (default): DROP TABLE IF EXISTS `Supplier`;
Executing (default): CREATE TABLE IF NOT EXISTS `Supplier` (`supplier_id` INTEGER auto_increment , `supplier_name` VARCHAR(60) NOT NULL, PRIMARY KEY (`supplier_id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Supplier`
Executing (default): DROP TABLE IF EXISTS `TreeSeed`;
Executing (default): CREATE TABLE IF NOT EXISTS `TreeSeed` (`seed_id` INTEGER NOT NULL auto_increment UNIQUE , `common_name` VARCHAR(45) NOT NULL UNIQUE, `species_name` VARCHAR(45) NOT NULL UNIQUE, `family` VARCHAR(45) NOT NULL, `seed_cost_incl_VAT` DOUBLE PRECISION(4,2) NOT NULL, `quantity_in_stock` INTEGER NOT NULL, `seed_number_per_pack` INTEGER NOT NULL, `colour` VARCHAR(20) NOT NULL, `hardiness` VARCHAR(20) NOT NULL, `soil_type` VARCHAR(60) NOT NULL, `soil_acidity` VARCHAR(60) NOT NULL, `description` TEXT NOT NULL, `tree_image1` BLOB NOT NULL, `tree_image2` BLOB, `tree_image3` BLOB, `seedcompany_id` INTEGER, PRIMARY KEY (`seed_id`), FOREIGN KEY (`seedcompany_id`) REFERENCES `Supplier` (`supplier_id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `TreeSeed`
All models made 

> Blockquote

(NOTE IT SAYS ABOVE THE MODELS HAVE BEEN MADE)
1
  • Please add the actual error messages for both methods
    – Anatoly
    Commented Jul 4 at 19:16

1 Answer 1

0

You have several issues here:

  1. Always indicate the same foreignKey option in both counterpart associations (hasMany/belongsTo):
Supplier.hasMany(TreeSeed,{
    foreignKey: 'seedcompany_id',
});
TreeSeed.belongsTo(Supplier,{
    foreignKey: 'seedcompany_id',
})

and you don't need to indicate targetKey if it's a PK.

  1. You need to wait for Supplier records to be inserted before trying to insert TreeSeed records:
insertSuppliers().then(() => {
  insertTreeSeed()
});
  1. You can't guarantee that Supplier records' ids will be the ones you indicated in treeSeedData because you indicate autoincrement: true in the PK.
    There are at least two possible ways to solve this:
  • indicate supplier names in treeSeedData and replace them with ids passing created suppliers in insertTreeSeed and finding a matching supplier by its name.
  • similar approach but add a unique text code column to suppliers and use it in treeSeedData instead of names to match suppliers
const insertSuppliers = async () =>{
   try{
     const records = await Supplier.bulkCreate(suppliersData,{validate:true})
     return records
     console.log("Suppliers data successfully inserted:",records)
   }catch(error){
      return []
      console.error("Could not insert supplier records")
   }
};

const insertTreeSeed = async (suppliers) =>{
   try{
    // here you need to remap treeSeedData matching supplier names/codes to their ids
    const records = await TreeSeed.bulkCreate(treeSeedData)
     console.log("Treeseed data successfully inserted",records)
   }catch(error){
      console.error("Could not insert tree seed records")
   }
}
insertSuppliers().then(suppliers => {
  insertTreeSeed(suppliers);
}

6
  • I am not really understanding point 3. seedcompany_id references supplier_id. If suppliersData is fed in first that data would have supplier_ids for each record then seedcompany_id could reference those ids (1-29). The 2 options; are you saying to replace seedcompany_id with seedcompany_name then use a utility function to remap the name to the supplier_id and in the second approach you said add a text code to suppliers which I do not get
    – RendezYT
    Commented Jul 5 at 6:48
  • Hello I tried what you said and it did not work. Could you reply to me if you see this then I can show you what I tried.
    – RendezYT
    Commented Jul 5 at 7:35
  • p.3 says that DB generates ids for you so you can't predict the exact values in seed data. That's why it's safe to remap from names to ids as soon as you have suppliers already created
    – Anatoly
    Commented Jul 6 at 7:44
  • I made the changes you suggested but now I get ER_NO_SUCH_TABLE error. Please could you look at my question again (seed edits above in my question not your answer) where I have made the changes in tree_seeds.js (seedcompany_name not seedcompany_id), added utilities.js (in utility_funcs folder) to swap out seedcompany_name for seed_company_id, added the new terminal error I receive and made changes to server.js. I also used Model.create instead of bulkCreate as I read MYSQL does not support autoincrementing well. Been working on this a while but no breakthrough.
    – RendezYT
    Commented Jul 6 at 9:29
  • I also made the changes in index.js in the models folder too and still ER_NO_SUCH_TABLE
    – RendezYT
    Commented Jul 6 at 9:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.