如何实现多对多的关联在使用风帆通过? [英] How to implement many to many association using through in Sails?

查看:208
本文介绍了如何实现多对多的关联在使用风帆通过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的帆v0.11.2 MongoDB的3.2 在Mac OS X埃尔卡皮坦,我想要实现的 许多一对多 协会使用的 选项,目前尚未支持。

I'm using Sails v0.11.2 and MongoDB 3.2 on Mac OS X El Capitan and I'm trying to implement Many-To-Many association using Through option which isn't supported yet.

不过,谷歌上搜索,我发现这个水线Github的问题 elennaro ,一个github上的用户,给了我一个链接夫妇有一些例子:

However, googling I found this Waterline Github Issue and elennaro, a github user, gave me a couple of links with some examples:


  1. 首先,你

  2. 第二个

  1. First one
  2. Second one

我试图使其适应自己帆应用程序,但我不能让它的工作原理。我得到了控制台,但是,没有错误的记录或的中介表笔未创建只有表格文件它的表。

I have tried to adapt them to my own Sails app but I can't make it works. I got no errors on the console but the record or document on the intermediary table is not created only the Form document in it's table.

这是我的模型:

user.js的

module.exports = {
    schema: true,
    tableName: 'users',
    autoCreatedAt: false,
    autoUpdatedAt: false,

    attributes:
    {
        email               : { type: 'email', required: true, unique: true },
        encrypted_password  : { type: 'string' },
        reset_password_token: { type: 'string', defaultsTo: null},
        permission_level    : { type: 'integer', required: true, min: 1, max: 3, defaultsTo: 0 },
        belongs_to          : { type: 'string', required: true, defaultsTo: 0 },
        signin_count        : { type: 'integer', required: true, defaultsTo: 1 },
        status_active       : { type: 'boolean', required: true, defaultsTo: false },
        last_signin_at      : { type: 'datetime', defaultsTo: function (){ return new Date(); } },
        last_signin_ip      : { type: 'string', defaultsTo: '0.0.0.0' },

        // Add a reference to Person
        person_id:
        {
            model: 'person'
        },
        // Add a reference to Forms collection
        forms:
        {
            collection: 'form',
            via: 'user_id',
            through: 'userhasform'
        },
        has:
        {
            collection: 'userhasform',
            via: 'form_id'
        }
    }

};

Form.js

module.exports = {
    schema: true,
    tableName: 'forms',

    attributes:
    {
        name    : { type: 'string', required: true, unique: true },
        creator : { type: 'string', unique: false },
        sequence: { type: 'integer', autoIncrement: true },

        // Add a reference to Questions collection
        questions:
        {
            collection: 'question',
            via: 'form_id'
        },
        // Add a reference to the owners Users
        owners: {
            collection: 'user',
            via: 'form_id',
            through: 'userhasform'
        }
    }

};

UserHasForm.js

module.exports = {
    schema: true,
    tableName: 'users_have_forms',

    attributes:
    {
        to_edit     : { type: 'boolean' },
        to_delete   : { type: 'boolean' },
        user_id     : { model: 'user' },
        form_id     : { model: 'form' }
    }

};

控制器中,我创建一个表单,它应该是中介的文件是在连接表中创建为:

The controller in which I create a form and it is supposed the intermediary document is been created at the join table is:

FormController.js

module.exports = {
    create: function (req, res)
    {
        var ownerJson = {},
            tmpFolio;

        // Get the logged user to make the Folio and then create the form
        SessionService.getUser(req, createForm);
        // Callback function
        function createForm (err, session)
        {
            // If there's no logged user or any error
            if (err || !session)
            {
                console.log(err);
                return res.json(err.status, {error: err});
            }

            console.log('User to create Folio: ', session.id);

            ownerJson.owner_a = session.first_name;
            ownerJson.owner_b = session.second_name;
            ownerJson.owner_c = session.last_name;
            // Construct the Folio creator part like AVC
            tmpFolio = FolioService.generateFolio(ownerJson);

            Form.create({
                name: req.body.name,
                creator: tmpFolio
            })
            .then(function (form){
                if (err)
                {
                    console.log(err);
                    return res.json(err.status, {error: err});
                }

                // Create the jointable record
                var createdRecord = UserHasForm.create({
                        to_edit: true,
                        to_delete: true,
                        user_id: session.id,
                        form_id: form.id
                    })
                    .then(function (createdRecord){
                        if (err)
                        {
                            console.log(err);
                            return res.json(err.status, {error: err});
                        }

                        return createdRecord;
                    });

                return [form, createdRecord];
            })
            .spread(function (form, createdRecord){
                return res.json(200,
                {
                    message: 'The form was created successfuly!',
                    data: form,
                    sharing: createdRecord
                });
            })
            .fail(function (err){
                if (err)
                {
                    console.log(err);
                    res.json(err.status, {error: err});
                }
            });
        }
    },

};

当我运行这个code,我得到了一个错误:

When I run this code I got the next error:

[ReferenceError: UserHasForm is not defined]
Unhandled rejection TypeError: Cannot read property 'toString' of undefined

所以我想这不能找到模型,所以我一开始的下一行添加到模型:

So I suppose it can't find the model so I add the next line to the model at the beginning:

var UserHasForm = require('../models/UserHasForm');

现在我得到下一个错误:

And now I get the next error:

[TypeError: UserHasForm.create is not a function]

这一切是继<一个href=\"https://github.com/balderdashy/waterline/blob/master/test/unit/query/associations/manyToManyThrough.js\"相对=nofollow>第一个例子的名单上。

任何想法,为什么我得到这个错误?

Any idea why I'm getting this error?

任何形式的帮助将受到欢迎!

Any kind of help will be welcomed!

推荐答案

努力的例子很多好后,我终于找到了解决办法感谢 @elennaro 了解他的一切支持。整个谈话可以在链接,我们都在的主要问题的意见开始聊天被发现。

Well after trying to many examples finally I found the solution thanks to @elennaro for all his support. The whole conversation could be found in the link to the chat we both started under the main question's comments.

此外,我可以告诉你,在他(这是在上面的问题)提供的链接的例子中工作正常,问题是,我是用不支持这些例子显示功能的版本。

Also I can tell you that the examples in the links provided by him (which are in the question above) works fine, the problem was that the version I was using didn't support the features that those examples show.

基本上我所要做的就是安装最新版本为的NodeJS SailsJS 水线

Basically what I had to do is to install the most recent version for NodeJS, SailsJS and Waterline.

在我来说,我其实有下的:

In my case I actually have the next ones:


  • 节点V5.3.0

  • 帆v0.11.3

  • 水线v0.10.30

之后,我不得不做出一些改变,我的模型,并在结束时,他们是这样的:

After that I have to make some changes to my models and at the end they look like this:

user.js的

module.exports = {

    schema: true,
    tableName: 'users',
    autoCreatedAt: false,
    autoUpdatedAt: false,

    attributes:
    {
        // username         : { type: 'string', unique: true, minLength: 5, maxLength: 15 },
        email               : { type: 'email', required: true, unique: true },
        encrypted_password  : { type: 'string' },
        reset_password_token: { type: 'string', defaultsTo: null},
        permission_level    : { type: 'integer', required: true, min: 1, max: 3, defaultsTo: 0 },
        belongs_to          : { type: 'string', required: true, defaultsTo: 0 },
        signin_count        : { type: 'integer', required: true, defaultsTo: 1 },
        status_active       : { type: 'boolean', required: true, defaultsTo: false },
        last_signin_at      : { type: 'datetime', defaultsTo: function (){ return new Date(); } },
        last_signin_ip      : { type: 'string', defaultsTo: '0.0.0.0' },

        // Add a reference to Forms collection
        forms:
        {
            collection: 'form',
            via: 'user',
            through: 'userhasform'

            // dominant: true
        }
    }

};

Form.js

module.exports = {

    schema: true,
    tableName: 'forms',

    attributes:
    {
        name    : { type: 'string', required: true, unique: true },
        creator : { type: 'string', unique: false },
        sequence: { type: 'integer', autoIncrement: true },

        // Add a reference to the owners Users
        owners: {
            collection: 'user',
            via: 'form',
            through: 'userhasform'
        }
    }

};

UserHasForm.js

module.exports = {

    schema: true,
    tableName: 'users_have_forms',

    attributes:
    {
        to_edit     : { type: 'boolean' },
        to_delete   : { type: 'boolean' },
        user        : { model: 'User', foreignKey: true, columnName: 'user_id' },
        form        : { model: 'Form',  foreignKey: true, columnName: 'form_id' }
    }

};

FormController.js

Still the same as in the question

我希望它可以为任何人有用。并再次感谢@亚历山大Arutinyants您的支持!

I hope it could be useful for anybody. And once again thanks to @ Alexander Arutinyants for your support!

有任何问题,请发表评论!

Any question, please leave a comment!

这篇关于如何实现多对多的关联在使用风帆通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆