官术网_书友最值得收藏!

Creating Band schema

Let's create the schema that will store in the database the data of each band that the user creates in the system.

  1. Open terminal/shell and type the following command:
     sequelize model:create --name Band --attributes "name:string, description:string, album:string, year:string, UserId:integer"
    
  2. As in the previous step, two files were created, one for migration of data and another to be used as a Band model, as the following code:
          'use strict'; 
          module.exports = function(sequelize, DataTypes) { 
            var Band = sequelize.define('Band', { 
              name: DataTypes.STRING, 
              description: DataTypes.STRING, 
              album: DataTypes.STRING, 
              year: DataTypes.STRING, 
              UserId: DataTypes.INTEGER 
            }, { 
              classMethods: { 
                 associate: function(models) { 
                  // associations can be defined here 
              } 
            } 
          }); 
          return Band; 
          }; 
    

Creating associations between Band and User models

As the last step before using the schemes migration script, we will need to create the associations between the User model and the Band model. We will use the following associations:

Tip

You can find more about associations at the following link: http://docs.sequelizejs.com/en/latest/docs/associations/.

  1. Open the User.js model and add the following highlighted code:
          'use strict'; 
           module.exports = function(sequelize, DataTypes) { 
             var User = sequelize.define('User', { 
               name: DataTypes.STRING, 
               email: DataTypes.STRING 
             }, { 
               classMethods: { 
                 associate: function(models) { 
                  // associations can be defined here 
                  User.hasMany(models.Band); 
                } 
              } 
             }); 
           return User; 
          }; 
    
  2. Open the Band.js model and add the following highlighted code:
          'use strict'; 
           module.exports = function(sequelize, DataTypes) { 
             var Band = sequelize.define('Band', { 
               name: DataTypes.STRING, 
               description: DataTypes.STRING, 
               album: DataTypes.STRING, 
               year: DataTypes.STRING, 
               UserId: DataTypes.INTEGER 
             }, { 
               classMethods: { 
                  associate: function(models) { 
                  // associations can be defined here 
            Band.belongsTo(models.User); 
             } 
            } 
           }); 
           return Band; 
          }; 
    
主站蜘蛛池模板: 崇信县| 建昌县| 都兰县| 黄大仙区| 墨玉县| 庆阳市| 贡山| 荔浦县| 临漳县| 万州区| 招远市| 德庆县| 昌乐县| 惠州市| 梅州市| 崇礼县| 神农架林区| 九台市| 综艺| 榆树市| 乐山市| 达尔| 吉木萨尔县| 大余县| 上饶县| 思南县| 弥勒县| 泸州市| 罗源县| 余江县| 綦江县| 柳江县| 拜城县| 民丰县| 正宁县| 运城市| 弋阳县| 沁源县| 岳阳市| 广平县| 兰西县|