为什么续集5会这样做?

时间:2019-04-17 10:38:17

标签: javascript node.js express sequelize.js

美好的一天! 当我在模型用户和测试之间创建关联时,sequelize可以正常工作。 但是,当我想为测试和问题添加新的关联时,然后顺序添加新列(我的外键import React, { Component } from "react"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { Card, CardBody, CardTitle, CardFooter, CardSubtitle } from "reactstrap"; import { BarChart, Tooltip, Bar, ResponsiveContainer, Cell, XAxis, YAxis } from "recharts"; import "./PopularDaysInWeek.css"; import { get_device_width } from "../../../actions"; const data = [ { name: "Sun", uv: 12.174 }, { name: "Mon", uv: 13.298 }, { name: "Tue", uv: 13.679 }, { name: "Wed", uv: 12.799 }, { name: "Thu", uv: 11.777 }, { name: "Fri", uv: 11.468 }, { name: "Sat", uv: 11.571 } ]; const COLORS = [ "#d1cd70", "#5ab89e", "#26a0a7", "#a2da91", "#dfb054", "#ec983d", "#e7a145" ]; class PopularDaysInWeek extends Component { constructor(props) { super(props); this.getDeviceWidth = this.getDeviceWidth.bind(this); } componentDidMount() { this.getDeviceWidth(); window.addEventListener("resize", this.getDeviceWidth); window.addEventListener("load", this.getDeviceWidth); } getDeviceWidth() { this.props.get_device_width(); } render() { let yaspect = 5.35; let t_count = 0; let left = 10; let width = 15; if (this.props.device >= 1024) { t_count = 3; left = -28; width = 20 } if (this.props.device >= 1666) { yaspect = 7.24; t_count = 4; left = 10; } return ( <div> <Card className="popular-days-in-week-card"> <CardTitle className="popular-days-in-week-card-title"> Popular Days in the Week </CardTitle> <CardSubtitle className="popular-days-in-week-card-subtitle"> Hits </CardSubtitle> <CardBody> <ResponsiveContainer width="100%" height="100%" aspect={5.0 / yaspect} > <BarChart data={data} barGap={10} margin={{ top: 5, right: 0, left: left, bottom: 0 }}> <Tooltip /> <XAxis dataKey="name" type="category" interval={0} tick={<CustomizedAxisTick />} /> <YAxis tick={<CustomizedYAxisTick />} tickCount={t_count} /> <Bar dataKey="uv" fill="#8884d8" maxBarSize={width}> {data.map((entry, index) => ( <Cell key={`cell-${index + 1}`} fill={COLORS[index]} /> ))} </Bar> </BarChart> </ResponsiveContainer> <CardFooter className="popular-days-in-week-card-footer"> <div>Hits in the Y-axis</div> </CardFooter> </CardBody> </Card> </div> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ get_device_width }, dispatch); } function mapStateToProps(state) { return { device: state.device }; } export default connect( mapStateToProps, mapDispatchToProps )(PopularDaysInWeek); class CustomizedAxisTick extends Component { render() { const { x, y, payload } = this.props; return ( <g transform={`translate(${x},${y})`}> <text x={0} y={0} dy={16} textAnchor="end" fill="#666" className="customized-axis-tick-text" > {payload.value} </text> </g> ); } } class CustomizedYAxisTick extends Component { render() { const { x, y, payload } = this.props; return ( <g transform={`translate(${x},${y})`}> <text x={-22} y={y-2} className="customized-y-axis-tick-text"> {`${payload.value}M`} </text> </g> ); } } 和额外的test_id)。

为什么?

user.js

testId

test.js

module.exports = (sequelize, DataType) => {
  const User = sequelize.define('user', {
    username: {
      type: DataType.STRING,
      unique: true,
    },
    password: {
      type: DataType.STRING,
    },
  });

  User.associate = (models) => {
    User.hasMany(models.test, {
      foreignKey: 'id',
    });
  };

  return User;
};

question.js

module.exports = (sequelize, DataType) => {
  const Test = sequelize.define('test', {
    title: {
      type: DataType.STRING,
      unique: true,
      required: true,
    },

    description: {
      type: DataType.TEXT,
      required: true,
    },

    picture: { // picture link
      type: DataType.STRING,
    },
  });

  Test.associate = (models) => {
    Test.belongsTo(models.user, {
      foreignKey: 'user_id',
    });
  };

  Test.associate = (models) => {
    Test.hasMany(models.question, {
      foreign_key: 'id',
    });
  };

  return Test;
};

index.js

module.exports = (sequelize, DataType) => {
  const Question = sequelize.define('question', {
    title: {
      type: DataType.STRING,
      required: true,
    },
  });

  Question.associate = (models) => {
    Question.belongsTo(models.test, {
      foreignKey: 'test_id',
    });
  };
  return Question;
};

这些模型会生成一些SQL查询:

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
require('dotenv').config();

const config = process.env;
const basename = path.basename(module.filename);

const sequelize = new Sequelize({
  database: config.DB_NAME,
  username: config.DB_USER,
  password: config.DB_PASS,
  dialect: config.DB_DIALECT,
});
const db = {};

fs
  .readdirSync(__dirname)
  .filter(file => (file.indexOf('.') !== 0) && (file !== basename))
  .forEach((file) => {
    const model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach((modelName) => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

Object.keys(db).forEach((modelName) => {
  if ('loadScopes' in db[modelName]) {
    db[modelName].loadScopes(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

2 个答案:

答案 0 :(得分:1)

在所有模型中添加underscored: false

module.exports = (sequelize, DataType) => {
    const Question = sequelize.define('question', {
        title: {
            type: DataType.STRING,
            required: true,
        },
    },
        {
            underscored: false, // <---- add this in all your models
        });

    Question.associate = (models) => {
        Question.belongsTo(models.test, {
            foreignKey: 'test_id',
        });
    };
    return Question;
};

Sequelize Documentation reference

答案 1 :(得分:0)

我发现了一个问题。

  Test.associate = (models) => {
    Test.hasMany(models.question, {
      foreignKey: 'id', // was foreign_key: 'id' 
    });
  };

可能是自动创建反向关联的错误还是触发器? 但是我没有找到有关此的信息。