Dependency Chain: category -> shop => category in model sequelizejs while defining foreign key

Rashmi Jain

List of Error:

\Possibly unhandled Error: Cyclic dependency found. 'category' is dependent of itself. Dependency Chain: category -> shop => category
at visit (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:74:27)
at /home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:96:25
at Array.forEach (native)
at visit (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:95:20)
at /home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:96:25
at Array.forEach (native)
at visit (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:95:20)
at Toposort.self.sort (/home/rashmi/nodejs/node_modules/sequelize/node_modules/toposort-class/toposort.js:104:21)
at module.exports.ModelManager.forEachDAO (/home/rashmi/nodejs/node_modules/sequelize/lib/model-manager.js:88:21)
at /home/rashmi/nodejs/node_modules/sequelize/lib/sequelize.js:894:25

While running this file Model.js

var Category=sequelize.define("category",{
    categoryname :{
        type: Sequelize.STRING,
        validate:{isAlpha:true}
    }},
    {
        paranoid: true,
        freezeTableName: true, //modeltable name will be the same as model name
        comment: "I'm Category table!"
    });

var shop=sequelize.define("shop",{
    shopID:{
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
    },
    title: {
        type: Sequelize.STRING(100),
         allowNull: false,
        validate:{isAlpha: true} 
    },
    shopKeeperName:{
        type: Sequelize.STRING(100),
         allowNull: false,
        validate:{isAlpha: true} 
    },
    mobile :{
        type: Sequelize.CHAR(10),
         allowNull: false
    },
    city :{
        type: Sequelize.INTEGER,
         allowNull: false,
         references: "City",
         referencesKey: "cityId"
    },
    scategory :{
        type: Sequelize.STRING,
        allowNull: false,
        references: "category",
        referencesKey: "Id"
    },
    address :{
        type: Sequelize.TEXT,
        allowNull: false,
        validate:{ isAlphanumeric:true}
    },
    stock :{
        type: Sequelize.INTEGER,
        validate: {isInt: true}
    }
    },
    {
        paranoid: true,
        freezeTableName: true, //modeltable name will be the same as model name
        underscored: true,
        comment: "I'm Shop table!"
    });

state.hasMany(city);
city.belongsTo(state,{foreignKey: 'stateID'});

Agent.hasOne(city);
city.belongsTo(Agent);

Agent.hasOne(state);
state.belongsTo(Agent);

shop.hasOne(Category);
Category.belongsTo(shop);
sequelize.sync();

While defining shop model, I got the above errors. foreign key categoryid in shop, I'm not getting the exact reason, what it means by Shop is dependent on itself, dependency cycle.

Jan Aagaard Meier
shop.hasOne(Category);
Category.belongsTo(shop);

Creates a relation from category -> shop, while the scategory column creates a relation from shop -> category. Because the relation goes both ways, sequelize does not know which table to create first - both tables require the other table to be created first.

You probably need to reverse the relation to:

shop.belongsTo(Category);
Category.hasOne(shop);

Does a category only relate to a single shop? Otherwise you need Category.hasMany(shop); to enable the same category to be related to several shops.

Furthermore, you don't need to both add a column (scategory) and call association functions - one is enough. This should be sufficient:

shop.belongsTo(Category, { foreignKey: 'scategory' });

While removing scategory from the defintion of shop. To enforce that scategory cannot be null, you can do:

Shop.belongsTo(Category, { 
  foreignKey: { 
    allowNull: false, 
    name: 'scategory'
  }
});

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

Django get all foreign key names of a model

Using nested set model to store Hierarchical data in sqlite how can I move a category into another category

django count of foreign key model

Django 1.11 not recognising Foreign Key model assignments

Taxonomy Category Permalink

Get current Category Name on a page which filters posts by Category and custom meta_key

Designing Model with foreign key

Wordpress Category Page (unclickable)

WooCommerce wrong category count

How to assign foreign key related field while creating model objects

One model with 2 categories in Django. How do I display another category from the same model in html?

Category detection

Handling category, float and int type features while using LIME for model interpretation

several category classification with Keras

How to prefix parent category to child category php

Export products with Category Names

How to remove "Category: [category name]" from wordpress

Proper handling of Category model in Rails

Remove product category titles from shop page woocommerce

Foreign key to different model field in django

Wordpress Exclude Category

"Nenhum resultado de consulta para o modelo [App \ Shop \ Categories \ Category] 1"

extbase: map sys_category to model

pass the foreign key of a model in the url

Django url by category slug

Check if the message channel is in that category

Limit forms foreign key to a choices in related model

Filter products using Category Model in Django

conditional tag (is_shop(), is_product_category() and is_product())

TOP lista

  1. 1

    Não foi possível carregar o arquivo ou montagem 'System.Runtime.InteropServices.RuntimeInformation

  2. 2

    Cannot resolve symbol Apache in Intellij

  3. 3

    Dependency Chain: category -> shop => category in model sequelizejs while defining foreign key

  4. 4

    Adicionando leads objetivo remontar a "Erro ao criar feijão com o nome 'EntityManagerFactory'"

  5. 5

    Como faço para remover zeros à esquerda antes de um ponto decimal? O Excel está formatado, mas o Combobox em meu formulário de usuário os está adicionando

  6. 6

    Combobox border or arrow remove in tkinter

  7. 7

    PhpStorm: SCSS File Watcher - como desabilitar mapas de origem?

  8. 8

    Fazendo a média de várias séries temporais junto com intervalo de confiança (com código de teste)

  9. 9

    Falha do aplicativo Spring Boot - Erro pacote java não existe

  10. 10

    Rolando ListViews juntos

  11. 11

    Spin: erro, a versão do spin que gerou este pan.c assumiu um tamanho de palavra diferente (4 iso 8)

  12. 12

    ViewPager com vários filhos visíveis e maior selecionado

  13. 13

    Não foi possível comprar com a oferta de assinatura

  14. 14

    Como chamar um método de serviço com Thymeleaf

  15. 15

    Erro de compilação do gRPC usando Visual Studio 2019 C #

  16. 16

    R no erro MacOS: memória do vetor esgotada (limite atingido?)

  17. 17

    Defina a largura do elemento posicionado de forma absoluta para seu conteúdo (é apenas um texto)

  18. 18

    Python cria md5, atualização e hexdigest em uma linha

  19. 19

    Plotly: Como adicionar média e desvio padrão a uma figura create_displot?

  20. 20

    Veicule arquivos estáticos (JavaScript) com Struts 2

  21. 21

    C # HttpClient - posso forçar o fechamento da conexão?

quentelabel

Arquivo