1
ドキュメントごとに、targetKeysオプションを使用して別のモデルの特定の列にforeignKeyを作成できます。私は以下のモデルでこれを行うにしようとしています:targetKeyを使用して別のモデルへのforeignKeyの関連付けを定義します。
module.exports = function(sequelize, DataTypes) {
var Booking = sequelize.define("Booking", {
//id: {type:DataTypes.INTEGER, primaryKey:true}, // auto-generate
bookingId: {type:DataTypes.INTEGER, primaryKey:true},
accId: {type:DataTypes.INTEGER},
description: {type:DataTypes.STRING(128)},
amount: {type:DataTypes.DECIMAL(15,2), allowNull:false}, // 0:prepaid, 1:postpaid
schDate: {type:DataTypes.DATE, allowNull:false},
createdBy: {type:DataTypes.INTEGER, allowNull:false},
modifiedBy: {type:DataTypes.INTEGER, allowNull:false}
},
{
tableName: "user_bookings",
timestamps: true,
paranoid: true,
classMethods: {
associate: function(models) {
Booking.belongsTo(models.Account, {foreignKey:'accId', targetKey:'accId'});
}
}
}
);
return Booking;
};
そして、私の他表は次のようになります。これらのテーブルが作成されると
module.exports = function(sequelize, DataTypes) {
var Account = sequelize.define("Account", {
//id: {type:DataTypes.INTEGER, primaryKey:true}, // auth-generate
userId: {type:DataTypes.INTEGER, primaryKey:true},
accType: {type:DataTypes.CHAR(1), allowNull:false}, // 0:prepaid, 1:postpaid
category: {type:DataTypes.INTEGER}, // reserved for future use
isDefault: {type:DataTypes.BOOLEAN, defaultValue:false}, // Is this the default wallet, (if the user has many wallets.)
balance: {type:DataTypes.DECIMAL(15,2), defaultValue:null},
creditLimit: {type:DataTypes.DECIMAL(15,2), defaultValue:null},
creditConsumed: {type:DataTypes.DECIMAL(15,2), defaultValue:null},
createdBy: {type:DataTypes.INTEGER, allowNull:false},
modifiedBy: {type:DataTypes.INTEGER, allowNull:false},
createdAt: {type:DataTypes.DATE, allowNull:false, get:function(){return this.getDataValue('createdAt').getTime()/1000;}},
updatedAt: {type:DataTypes.DATE, allowNull:false, get:function(){return this.getDataValue('updatedAt').getTime()/1000;}}
},
{
tableName: "user_accounts",
timestamps: true,
paranoid: true,
}
);
return Account;
};
、私は最初のモデルが持っていることを期待しています第2のものに作成された外部キー。しかし、それは起こっていません。
マイuser_bookingsテーブルは、すべての参照せずにスタンドアロン表として示しています。私はここで間違って
mysql> desc user_bookings;
+-------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+-------+
| bookingId | int(11) | NO | PRI | 0 | |
| accId | int(11) | YES | | NULL | |
| description | varchar(128) | YES | | NULL | |
| amount | decimal(15,2) | NO | | NULL | |
| schDate | datetime | NO | | NULL | |
| createdBy | int(11) | NO | | NULL | |
| modifiedBy | int(11) | NO | | NULL | |
| createdAt | datetime | NO | | NULL | |
| updatedAt | datetime | NO | | NULL | |
| deletedAt | datetime | YES | | NULL | |
+-------------+---------------+------+-----+---------+-------+
10 rows in set (0.01 sec)
何をしているのですか?事前のおかげで...
を使用するときは、二回私のミス予約の定義を貼り付け
createdAt
とupdatedAt
などの属性を宣言する必要はありません。 – denisazevedoはい、タイプミスです。今修正されました。 –