代码之家  ›  专栏  ›  技术社区  ›  Boris K

bookshelf.js:一对多关系设置

  •  0
  • Boris K  · 技术社区  · 8 年前

    我在用MySQL的ORM使用书架。我有终点站和组织。每个端点都属于一个组织,并且一个组织有许多端点。我正在尝试获取与其关联组织的终结点列表。这将返回以下错误:

    “必须为Endpoint BelongsTo关系定义有效的目标模型”

    这是我的fetchall请求:

    Endpoint
                .where('organization_id', req.user.attributes.organization_id)
                .fetchAll({require: true,withRelated: ['settings', 'organization']})
                .then((endpoints) => {
                    ReS(res, {
                        endpoints
                    }, 200);
                })
    

    这是我的端点模型:

    'use strict';
    
    const bookshelf = require('../config/bookshelf_instance');
    const Organization = require('./organization');
    const Settings = require('./endpoint_settings');
    const Group = require('./endpoint_group');
    
    module.exports = bookshelf.Model.extend({
        tableName: 'endpoint',
        organization () {
            return this.belongsTo(Organization, 'id');
        },
        settings () {
            return this.hasOne(Settings, 'id');
        },
        group () {
            return this.belongsToMany(Group, 'map_endpoint_endpoint_group');
        }
    });
    

    这是我的组织模式:

    'use strict';
    
    const bookshelf = require('../config/bookshelf_instance');
    const Endpoint = require('./endpoint');
    const User = require('./user');
    const Group = require('./endpoint_group');
    
    module.exports = bookshelf.Model.extend({
        tableName: 'organization',
        endpoints () {
            return this.hasMany(Endpoint, 'organization_id');
        },
        users () {
            return this.hasMany(User, 'organization_id');
        },
        groups () {
            return this.hasMany(Group, 'organization_id');
        }
    });
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   devius    8 年前

    你应该移除 id 从端点模型的关系规范来看,这似乎是主键,而不是外键。外键也是 organization_id 默认情况下这是你想要的。它应该与你拥有的相反关系相匹配( hasMany 在这种情况下)。

    从文档中,第二个参数 belongsTo 是:

    这个模型中的外键。默认情况下,foreignkey被假定为目标模型表名的单数形式,后跟_id。

    目标模型的表名为 organization ,这意味着外键是 组织ID 默认情况下。