代码之家  ›  专栏  ›  技术社区  ›  Black Mamba

如何在loopback4中添加外键?

  •  0
  • Black Mamba  · 技术社区  · 7 年前

    As per this discussion 和其他资源可用于v3及更早版本,但我找不到直接使用添加外键的方法 环回4 因此,当我从模型中迁移DB时,仍然有外键约束。

    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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Marvin Irwin    7 年前

    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

    推荐文章