The CreateForeignKey method facilitates the creation of a foreign-key on a table column in the database. A foreign-key constraint is created on the assigned column, thereby limiting its allowable values to those found in the table.column referenced in the foreign-key declaration.
In general, it is more desirable to declare foreign-keys in the model via the “fkey:” ‘sqac:’ tag than to call this method directly.
Parameter | Description |
---|---|
i interface{} | Accepts the go struct type of the table on which the foreign-key is being declared. For example:If table column product.warehouse_id is being assigned a foreign-key of table column warehouse.id, this parameter would expect to be provided with go type Product{}. |
ft string | The database table name of the table on which the foreign-key is being declared. For example:If table column product.warehouse_id is being assigned a foreign-key of table column warehouse.id, this parameter should be provided with “product”. |
rt string | The database table name of the table on which the foreign-key will refer to. For example:If table column product.warehouse_id is being assigned a foreign-key of table column warehouse.id, this parameter should be provided with “warehouse”. |
ff string | The database name of the column on which the foreign-key is being declared. For example:If table column product.warehouse_id is being assigned a foreign-key of table column warehouse.id, this parameter should be provided with “warehouse_id”. |
rf string | The database name of the column on which the foreign-key will refer to. For example:If table column product.warehouse_id is being assigned a foreign-key of table column warehouse.id, this parameter should be provided with “id”. |
A sample call using the scenario described in the Parameters table follows:
type Warehouse struct {
ID uint64 `db:"id" json:"id" sqac:"primary_key:inc;start:40000000"`
City string `db:"city" json:"city" sqac:"nullable:false;default:Calgary"`
Quadrant string `db:"quadrant" json:"quadrant" sqac:"nullable:false;default:SE"`
}
type Product struct {
ID uint64 `db:"id" json:"id" sqac:"primary_key:inc;start:95000000"`
ProductName string `db:"product_name" json:"product_name" sqac:"nullable:false;default:unknown"`
ProductCode string `db:"product_code" json:"product_code" sqac:"nullable:false;default:0000-0000-00"`
UOM string `db:"uom" json:"uom" sqac:"nullable:false;default:EA"`
WarehouseID uint64 `db:"warehouse_id" json:"warehouse_id" sqac:"nullable:false"`
}
err := Handle.CreateForeignKey(Product{}, "product", "warehouse", "warehouse_id", "id")
...
...