Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Liquibase: How to Set Foreign Key(s) Constraint in Column Tag?

How can I configure foreign keys through column tag attributes foreignKeyName and references? The only example I've found demonstrates how to add foreign keys after the fact.

like image 802
Ari Avatar asked Jul 13 '14 00:07

Ari


People also ask

What is the foreign key constraint?

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.

What is a foreign key column?

A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby establishing a link between them.

How do you name a foreign key?

Foreign key is a field in the database table that is a primary key in other tables. The naming conventions for a foreign key constraint should have an "FK_" prefix, followed by the target table name, followed by the source table name. The syntax should be "FK_<TargetTable>_<SourceTable>".


1 Answers

Use a nested <constraints> tag in your column tag.

Example:

<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> 
like image 68
Nathan Voxland Avatar answered Nov 08 '22 19:11

Nathan Voxland