Black Mamba
Black Mamba

Reputation: 15545

How to add foreign key in loopback4?

As per this discussion and other resources are available for v3 and earlier but I'm not able to find a method to add foreign key directly with loopback 4 so that when I migrate DB from the models I still have the foreign key constraint.

Here's what I have till now but I'm not able to get a foreign key when migration is done.

My model:

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

My repository:

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,
    );
  }
}

I'm using MySQL as datasource. But when I run npm run migrate the foreign keys aren't created.

I want to have toDoListId column as a foreign key to the todo model. Here's the tutorial I'm following

Upvotes: 0

Views: 1819

Answers (2)

khlilturki97
khlilturki97

Reputation: 51

found the answer here, besides adding the settings to @model annotation, you have to change to specify in which order tables should be created

Upvotes: 1

Marvin Irwin
Marvin Irwin

Reputation: 1010

It looks like foreign keys must be defined in the model settings. I'm not sure if this was the case for lb 2 & 3, but I was able to get this working in lb4.

Also, I think you have to create this particular key on the Todo model.

@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

Upvotes: 1

Related Questions