这是我的模型的样子
"name": "mClass",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"mClassName": {
"type": "string",
"required": true,
"index": {
"unique": true
}
},
"mClassUrl": {
"type": "string"
},
"mCreatedBy": {
"type": "string",
"required": true
},
"mCreatedAt": {
"type": "date",
"required": true,
"default": "$now"
},
"mUpdatedAt": {
"type": "date"
},
"mDeletedAt": {
"type": "date"
}
},
"validations": [],
"relations": {},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$unauthenticated",
"permission": "DENY"
}
],
"methods": {}
}
我想使类名唯一。我尝试了index:{unique:true},但似乎无法正常工作,因为我仍然可以创建具有相同名称的类。请帮助我进行哪些更改。
答案 0 :(得分:0)
答案 1 :(得分:0)
您需要做的是在model.json中定义索引:
"indexes": {
"indexName": {
"keys": {
"mClassName": 1
},
"options": {
"unique": true
}
}
}
然后,当服务器启动时,您需要在数据源上运行自动更新,最适合的地方是引导脚本,例如。 ./server/boot/db-autoupdate.js
:
'use strict';
module.exports = async function(app) {
// this will trigger the database structure update, like creating indexes (which is not handled by auto-migrate module
await app.dataSources.db.autoupdate();
};
答案 2 :(得分:0)
或者,在您的 mClass.js 中,您可以执行以下操作:
module.exports = function (mClass) {
mClass.validatesUniquenessOf('mClassName');
};
答案 3 :(得分:0)
如果有人正在寻找此问题的Loopback v4解决方案。在Loopback v4中,您可以使用“ index:{unqiue:true}”来修改@property注释:
@model()
export class Client extends Entity {
@property({
type: 'string',
required: true,
index: {
unique: true,
},
})
name: string;
}