水线ORM外键错误

时间:2015-07-27 03:55:14

标签: mysql node.js waterline

我对NodeJS完全不熟悉。我正在尝试使用mysql数据库构建我的第一个快速应用程序。我没有使用Sails,但我读了一些使用Waterline ORM的建议。但是,我在尝试初始化ORM时遇到问题。这是我在mysql中的数据库模式:

CREATE TABLE IF NOT EXISTS `c` (
  `c_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `d_id` int(11) UNSIGNED NOT NULL,
  `name` varchar(255) NOT NULL,
   PRIMARY KEY  (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `d` (
  `d_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `c_id` int(11) UNSIGNED NULL,
  `name` varchar(255) NOT NULL,
   PRIMARY KEY  (`d_id`),
   CONSTRAINT `d_ibfk_1` FOREIGN KEY (`c_id`) REFERENCES `c`(`c_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE c ADD CONSTRAINT `c_ibfk_1` FOREIGN KEY (`d_id`) REFERENCES `d`(`d_id`) ON DELETE CASCADE;

这是我的Node JS代码

var express = require("express");
var app  = express();
var Waterline = require("waterline");

//console.log(new homer());
var orm = new Waterline();


//////////////////////////////////////////////////////////////////
// WATERLINE CONFIG
//////////////////////////////////////////////////////////////////

// Require any waterline compatible adapters here
var diskAdapter = require('sails-disk'),
    mysqlAdapter = require('sails-mysql');


// Build A Config Object
var config = {

  // Setup Adapters
  // Creates named adapters that have have been required
  adapters: {
    'default': diskAdapter,
    disk: diskAdapter,
    mysql: mysqlAdapter
  },

  // Build Connections Config
  // Setup connections using the named adapter configs
  connections: {
    myLocalDisk: {
      adapter: 'disk'
    },

    myLocalMySql: {
      adapter: 'mysql',
      host: 'localhost',
      database: 'waterline_error',
      user: 'weruser',
      password: 'migjiii322'
    }
  }

};

var C = Waterline.Collection.extend({
  tableName: 'c',
  identity: 'c',
  connection: 'myLocalMySql',

  attributes: {
    c_id: {type:'integer'},
    name: {type:'string'}
  }
});

orm.loadCollection(C);

app.listen(3000,function(){
  console.log("Running Server on Port 3000.");

    orm.initialize(config, function(err, models) {
      if(err) throw err;
      app.models = models.collections;
      app.connections = models.connections;

      app.models.c.find().exec(function(err,models){

        if(err) return res.json({ err: err }, 500);
        console.log(models);

      });


    });

});

当我运行此代码时,出现以下错误:

          if(err) throw err;
                        ^
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails

如何解决此错误,使底部附近的.find()函数实际被触发?

0 个答案:

没有答案