Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Include associations from json files with sequelize-fixtures?

Hello mates,

I'm pretty new to sequelizejs and just trying to use it. I have problems with the creation of example datasets using sequelize-fixtures.

My models are created like so:

User.js (without beforeCreate, beforeUpdate hooks)

'use strict';
module.exports = function (sequelize, DataTypes) {
    var User = sequelize.define('User', {
        email: {type: DataTypes.STRING, allowNull: false},
        password: {type: DataTypes.STRING, allowNull: false},
        active: {type: DataTypes.BOOLEAN, default: false}
    });
    return User;
};

Role.js

'use strict';
module.exports = function (sequelize, DataTypes) {
    var Role = sequelize.define('Role', {
        title: {type: DataTypes.STRING, allowNull: false},
        description: {type: DataTypes.STRING, allowNull: true},
        code: {type: DataTypes.STRING, allowNull: false}
    });
    return Role;
};

After importing models into the models object I have created the associations between them:

models.User.belongsToMany(models.Role, {through: 'UserRole', constraints: true});
models.Role.belongsToMany(models.User, {through: 'UserRole', constraints: true});

And I have loaded the example data from json files used with the structure as the documentation said but the userroles table which was created automagically by sequelize remains empty.

The fixture json file contains the following:

[
    {
        "model": "Role",
        "data": {
            "title": "Administrator",
            "description": "Administrator users",
            "code": "RIGHT_ADMIN"
        }
    },
    {
        "model": "Role",
        "data": {
            "title": "Manager",
            "description": "Manager users",
            "code": "RIGHT_MANAGEMENT"
        }
    },
    {
        "model": "User",
        "keys": [
            "id"
        ],
        "data": {
            "id": 0,
            "email": "[email protected]",
            "password": "admin",
            "active": true
        },
        "roles":[1,2]
    }
]

And the fixture loading will be called after when db synced: force: true, left in it for developing reasons only

db.sync({force: true}).then(function () {

    //load fixtures
    SequelizeFixtures.loadFile('fixtures/*.json', models).then(function () {
        console.dir("DEV DATA CREATED SUCCESSFULLY");
    });
});

My problem is that the userroles table which was created by the association of User and Role model always remains empty after running the fixtures.

like image 360
Dániel Sebestyén Avatar asked Oct 31 '15 13:10

Dániel Sebestyén


People also ask

How do you do associations in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

How do I store JSON in Sequelize?

Create a database and a Schema: var Sequelize = require('sequelize'), JsonField = require('sequelize-json'), db, User; db = new Sequelize('database', 'username', 'password', { dialect: 'sqlite', logging: false }); User = db. define('User', { username: Sequelize. STRING, jsonField: JsonField(db, 'User', 'jsonField') });

How do you use belongsTo in Sequelize?

You can make the Task model belongs to the User model by calling the belongsTo() method from the Task model like this: Task. belongsTo(User); The belongsTo() method above will associate the Task model with the User model, adding the UserId attribute to the Task model as the foreign key constraint.

How do I get data from two tables in Sequelize?

There are two ways you can create JOIN queries and fetch data from multiple tables with Sequelize: Create raw SQL query using sequelize. query() method. Associate related Sequelize models and add the include option in your Sequelize query method.


1 Answers

FIGURED OUT THE STUFF

It turnt out that the sequelize fixture document said that the many2many relation values could be defined outside the data of a given model record in the json files.

The solution is to find the relations association key in the $Model.associations object of the Model and use that as a key inside the data object.

In short:

this

models.User.belongsToMany(models.Role, {through: 'UserRole', constraints: true});
models.Role.belongsToMany(models.User, {through: 'UserRole', constraints: true});

is created an association 'Roles' of the User model and a 'Users' of the Role model.

Now according this the json record object should look like this:

{
    "model": "User",
    "keys": [
        "id"
    ],
    "data": {
        "id": 0,
        "email": "[email protected]",
        "password": "admin",
        "active": true,
        "Roles":[1,2]
    }
}

Here is a gist I'have made to show how to use it.

Hope this will help other users of sequelize and sequelize-fixtures

like image 127
Dániel Sebestyén Avatar answered Sep 28 '22 07:09

Dániel Sebestyén