问题描述
在进行 Running on relational databases 的练习时, 使用npm run migrate
根据API 的model 定义, 在数据库建表的时候, 报 Cannot migrate database schema error: 在外键约束中的关联字段 “todoListId” 不存在 的错误
解决方法
确认跟教程无误的情况下, 建立外键约束时, 将foreignKey的值改为全小写, 如下是完整的外键约束
postgresql只有小写的字段名,用大写写的字段名它会自动转换为小写的。
import {belongsTo, Entity, model, property} from '@loopback/repository';
import {TodoList, TodoListWithRelations} from './todo-list.model';
@model({
settings: {
postgresql: {
schema: 'lb4', // 指定schema
table: 'todo' // 表名
},
// 外键约束
foreignKeys: {
fk_todo_todoListId: {
name: 'fk_todo_todoListId', // 外键别名
entity: 'TodoList', // 关联实体
entityKey: 'id', // 参照约束
foreignKey: 'todolistid', // 官方文档是todoListId, 此处须改为全小写
},
}
}
})
export class Todo extends Entity {
//etc.
@belongsTo(() => TodoList)
todoListId: number;
constructor(data?: Partial<Todo>) {
super(data);
}
}
export interface TodoRelations {
// describe navigational properties here
todoList?: TodoListWithRelations
}
export type TodoWithRelations = Todo & TodoRelations;
npm run rebuild && npm run migrate 生成的表
ER图
TODO表中的外键:
Loopback4 官方练习链接: https://loopback.io/doc/en/lb4/PostgreSQL-connector.html#auto-migrateauto-update-models-with-foreign-keys