Liquibase:如何在列标签中设置外键约束?

2022-08-31 15:21:19

如何通过列标记属性和 ?我找到的唯一示例演示了如何在事后添加外键foreignKeyNamereferences


答案 1

在列标记中使用嵌套标记。<constraints>

例:

<changeSet id="SAMPLE_1" author="alice">
    <createTable tableName="employee">
        <column name="id" type="int" autoIncrement="true">
            <constraints primaryKey="true"/>
        </column>
        <column name="first_name" type="varchar(255)"/>
        <column name="last_name" type="varchar(255)">
            <constraints nullable="false"/>
        </column>
    </createTable>
</changeSet>

<changeSet id="create address table" author="bob">
    <createTable tableName="address">
        <column name="id" type="int" autoIncrement="true">
            <constraints primaryKey="true"/>
        </column>
        <column name="line1" type="varchar(255)">
            <constraints nullable="false"/>
        </column>
        <column name="line2" type="varchar(255)"/>
        <column name="city" type="varchar(100)">
            <constraints nullable="false"/>
        </column>
        <column name="employee_id" type="int">
            <constraints nullable="false" foreignKeyName="fk_address_employee" references="employee(id)"/>
        </column>
    </createTable>
</changeSet>

答案 2

您必须添加外部约束,例如:

- changeSet:
    id: create_account_table
    author: ankit
    changes:
    - createTable:
        tableName: account
        columns:
        - column:
            name: accn_id
            type: uuid
            constraints:
              primaryKey: true
              primaryKeyName: pk_account
- changeSet:
    id: create_table_abc
    author: ankit
    changes:
    - createTable:
        tableName: abc
        columns:
        - column:
            name: id
            type: uuid
            constraints:
              primaryKey: true
              primaryKeyName: pk_abc
        - column:
            name: accn_id
            type: UUID
            constraints:
              nullable: false
              foreignKeyName: fk_abc_account
              references: account(accn_id)

推荐