使用旧表
虽然开箱即用的 Sequelize 似乎有点有态度,但通过定义(否则生成的)表和字段名称,可以轻松处理旧表并向前证明你的应用。
¥While out of the box Sequelize will seem a bit opinionated it's easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names.
表
¥Tables
class User extends Model {}
User.init(
{
// ...
},
{
modelName: 'user',
tableName: 'users',
sequelize,
},
);
字段
¥Fields
class MyModel extends Model {}
MyModel.init(
{
userId: {
type: DataTypes.INTEGER,
field: 'user_id',
},
},
{ sequelize },
);
主键
¥Primary keys
默认情况下,Sequelize 会假设你的表具有 id
主键属性。
¥Sequelize will assume your table has a id
primary key property by default.
要定义你自己的主键:
¥To define your own primary key:
class Collection extends Model {}
Collection.init(
{
uid: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true, // Automatically gets converted to SERIAL for postgres
},
},
{ sequelize },
);
class Collection extends Model {}
Collection.init(
{
uuid: {
type: DataTypes.UUID,
primaryKey: true,
},
},
{ sequelize },
);
如果你的模型根本没有主键,你可以使用 Model.removeAttribute('id');
¥And if your model has no primary key at all you can use Model.removeAttribute('id');
没有主键的实例仍然可以使用 Model.findOne
和 Model.findAll
检索。虽然目前可以使用它们的实例方法(instance.save
、instance.update
等),但这样做会导致细微的错误,并计划在未来的重大更新中删除。
¥Instances without primary keys can still be retrieved using Model.findOne
and Model.findAll
.\ While it's currently possible to use their instance methods (instance.save
, instance.update
, etc…), doing this will lead to subtle bugs,
and is planned for removal in a future major update.
如果你的模型没有主键,则需要使用以下实例方法的静态等效项,并提供你自己的 where
参数:
¥If your model has no primary keys, you need to use the static equivalent of the following instance methods, and provide your own where
parameter:
-
instance.save
:Model.update
-
instance.update
:Model.update
-
instance.reload
:Model.findOne
-
instance.destroy
:Model.destroy
-
instance.restore
:Model.restore
-
instance.decrement
:Model.decrement
-
instance.increment
:Model.increment
外键
¥Foreign keys
// 1:1
Organization.belongsTo(User, { foreignKey: 'owner_id' });
User.hasOne(Organization, { foreignKey: 'owner_id' });
// 1:M
Project.hasMany(Task, { foreignKey: 'tasks_pk' });
Task.belongsTo(Project, { foreignKey: 'tasks_pk' });
// N:M
User.belongsToMany(Role, {
through: 'user_has_roles',
foreignKey: 'user_role_user_id',
});
Role.belongsToMany(User, {
through: 'user_has_roles',
foreignKey: 'roles_identifier',
});