【问题标题】:Waterline associations, change foreign key?水线关联,改外键?
【发布时间】:2014-05-15 17:29:18
【问题描述】:

最新的水线现在支持关联。这是一个一对多的例子

// A user may have many pets
var User = Waterline.Collection.extend({

  identity: 'user',
  connection: 'local-postgresql',

  attributes: {
    firstName: 'string',
    lastName: 'string',

    // Add a reference to Pets
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
});

var Pet = Waterline.Collection.extend({

  identity: 'pet',
  connection: 'local-postgresql',

  attributes: {
    breed: 'string',
    type: 'string',
    name: 'string',

    // Add a reference to User
    owner: {
      model: 'user'
    }
  }
});

这会在宠物集合上创建一个名为 owner 的字段。除了使用现有数据库之外,这会很好。它称之为外键owner_id

是否有覆盖数据库中使用的字段名称?

【问题讨论】:

    标签: foreign-keys associations sails.js waterline


    【解决方案1】:

    您可以通过设置columnName 属性来更改用于任何模型属性的列名:

      attributes: {
        breed: 'string',
        type: 'string',
        name: 'string',
    
        // Add a reference to User
        owner: {
          columnName: 'owner_id',
          model: 'user'
        }
      }
    

    还请注意,在 Sails 中定义模型时,不应直接从 Waterline 扩展,而只需将模型文件保存在 /api/models 中并使用适当的名称,例如User.js:

    module.exports = {
    
       attributes: {
          breed: 'string',
          type: 'string',
          name: 'string',
    
          // Add a reference to User
          owner: {
             model: 'user',
             columnName: 'owner_id'
          }
       }
    }
    

    并让 Sails / Waterline 为您处理身份和连接,除非您真的想覆盖默认值。

    【讨论】:

    • 该代码是从水线文档中复制的。我的模型不从水线延伸。但我确实想知道是否需要这样做,所以感谢您提供的额外信息。
    • Waterline 文档的真正目的是在 Sails 之外使用 Waterline;对于 Sails v0.10,您可以使用 model docs on the web site
    • 哦哇!...我不知道你可以去beta.sailsjs.org!!!我一直在到处寻找文档......谢谢!
    猜你喜欢
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    相关资源
    最近更新 更多