7

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

// 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

无论如何要覆盖数据库中使用的字段名称?

4

1 回答 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 为您处理身份和连接,除非您真的想覆盖默认值。

于 2014-04-03T21:46:24.370 回答