【问题标题】:Loopback automigrate many to many环回自动迁移多对多
【发布时间】:2017-06-20 22:23:56
【问题描述】:

我们目前正在尝试编写数据样本创建脚本,以便将一些数据插入到我们的数据库中以测试 API。我们有一些不通过另一个模型的多对多关系,因此环回生成关联表及其键(实体 1 fk,实体 2 fk)。

我们的示例数据存储在 JSON 文件中,我们稍后会加载这些文件并将它们传递给数据源自动迁移函数。

我们遇到的问题是数据源无法迁移存储在关联表中的数据(即使它们存在于数据库中),因为它们不作为正确的 Loopback 模型存在。

例如,以实体 Customer 和 CustomerGroup 为例。一个客户可以属于多个客户组,一个客户组可以有多个客户,因此以下 JSON 将用于关联生成的 CustomerGroupCustomer 表:

[
    {"CustomerGroupId": "1", "CustomerId": "1"}, 
    {"CustomerGroupId": "2", "CustomerId": "2"},
    {"CustomerGroupId": "1", "CustomerId": "3"}
]

有没有办法使用默认方法迁移这些数据,还是我们应该寻找解决方法?

【问题讨论】:

    标签: loopbackjs


    【解决方案1】:

    所以我想通了!我之前使用这个函数来自动迁移我的表:

    function automigrate(connection, table, data) {
        app.models[table].create(data, function(err, models) {
            if (err) throw err; console.log('|- ' + table);
        });
    }
    

    事实证明,app 对象不知道数据源生成的多对多表,而数据源知道。因此,您需要做的就是从数据源对象而不是应用程序中检索模型:

    function automigrate(connection, table, data) {
        connection.adapter._models[table].model.create(data, function(err, models) {
            if (err) throw err; console.log('|- ' + table);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-23
      • 1970-01-01
      • 2014-08-01
      • 2023-04-07
      • 2021-12-27
      • 2011-08-30
      • 1970-01-01
      • 2016-03-30
      • 2018-06-24
      相关资源
      最近更新 更多