水线关联,更改外键?

7
最新的Waterline现在支持关联。这里是一个一对多的例子。
// 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。是否有任何方法可以覆盖数据库中使用的字段名称?
1个回答

8

您可以通过设置 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文档中复制的。我的模型并不是从Waterline继承的。但我曾经想知道是否需要这样做,所以感谢您提供的额外信息。 - InternalFX
2
Waterline文档的真正目的是为了在Sails之外使用Waterline;对于Sails v0.10,您可以使用网站上的模型文档。 - sgress454
1
哇!我不知道你可以去 http://beta.sailsjs.org !!!我一直在到处搜寻文档...谢谢! - InternalFX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接