sdepold/sequelize — pull request #111 by hiddentao (2011-11-22 09:31:55+00:00)
Title: Make it possible to use a field as both primary and foreign key

Sascha, the changes attached (with tests) make it possible for primary keys to be used as foreign keys too. For example:

```
var User = sequelize.define('user', {
name: Sequelize.STRING
},{
underscored : true
})

var Profile = sequelize.define('profile', {
user_id: {
type: Sequelize.INTEGER,
primaryKey: true
},
dob: Sequelize.DATE
},{
underscored : true
})

var Profile2 = sequelize.define('profile2', {
dob: Sequelize.DATE
},{
underscored : true
})

User.hasOne(Profile)
User.hasOne(Profile2)

```

In the above definitions, sequelize would normally replace the the `user_id` field in `Profile` with a plain INTEGER field for use as the foreign key. This attached code changes now leave such primary keys intact and allow them to be used as foreign keys. If the `user_id` field isn't already defined (see `Profile2`) then sequelize will still create it as normal for foreign key purposes. The new changes also work for `belongsTo` and `hasMany` associations. Note that the `hasMany` associations which require a new table to hold the relationship aren't affected by these changes.

The tests check that combined primary and foreign key fields as defined above by the user are honoured when creating new models using `build()` and when creating the tables in the database. The tests also check that only INTEGER fields may be used as foreign keys. Thus, sequelize will reject the following definition:

```
var User = sequelize.define('user', {
name: Sequelize.STRING
},{
underscored : true
})

var Profile = sequelize.define('profile', {
user_id: {
type: Sequelize.STRING,
primaryKey: true
},
dob: Sequelize.DATE
},{
underscored : true
})

User.hasOne(Profile) // will fail at this point because Profile.user_id isn't of INTEGER type

```