gpt4 book ai didi

mysql - 如何在loopback4中添加外键?

转载 作者:行者123 更新时间:2023-11-29 09:53:48 25 4
gpt4 key购买 nike

As per this discussion其他资源可用于 v3 及更早版本,但我无法找到直接使用 loopback 4 添加外键的方法,这样当我从模型迁移数据库时,我仍然具有外键约束.

这是我到目前为止所拥有的,但迁移完成后我无法获得外键。

我的模型:

export class TodoList extends Entity {
@hasMany(() => Todo, { keyTo: 'todoListId' })
todos?: Todo[];
@property({
type: 'string',
})
todoListId: number;

我的存储库:

export class TodoListRepository extends DefaultCrudRepository<
TodoList,
typeof TodoList.prototype.id
> {
public readonly todos: HasManyRepositoryFactory<
Todo,
typeof Todo.prototype.id
>;
constructor(
@inject('datasources.todo') dataSource: TodoDataSource,
@repository.getter(TodoRepository)
protected todoRepositoryGetter: Getter<TodoRepository>,
) {
super(TodoList, dataSource);
this.todos = this.createHasManyRepositoryFactoryFor(
'todos',
todoRepositoryGetter,
);
}
}

我使用 MySQL 作为数据源。但是当我运行 npm run migrate 时,不会创建外键。

我希望将 toDoListId 列作为 todo 模型的外键。 Here's the tutorial I'm following

最佳答案

看起来必须在模型设置中定义外键。我不确定 lb 2 和 3 是否属于这种情况,但我能够在 lb4 中实现此功能。

此外,我认为您必须在 Todo 模型上创建这个特定的键。

@model({
settings: {
"foreignKeys": {
"todoListId": {
"name": "todoListId",
"foreignKey": "todoListId",
"entityKey": "id",
"entity": "TodoList"
}
}
}
})
export class Todo extends Entity { ...

https://loopback.io/doc/en/lb3/MySQL-connector.html#auto-migrateauto-update-models-with-foreign-keys

关于mysql - 如何在loopback4中添加外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com