Creando un migración en Laravel 5.4 con MySQL 5.6 Puedo añadir una referencia externa perfectamente si es sobre el Id de otra tabla, pero no puedo añadirla sobre un indice string.
Esta funciona bien sobre el campo Id
CREATE TABLE `stock` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`component_id` int(10) unsigned NOT NULL,
`code` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`quantity` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `stock_component_code_code_unique` (`component_code`,`code`),
KEY `stock_component_id_foreign` (`component_id`),
CONSTRAINT `stock_component_id_foreign` FOREIGN KEY (`component_id`) REFERENCES `components` (`id`) ON DELETE CASCADE
)
Pero quiero sobre el campo VARCHAR
CREATE TABLE `stock` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`component_id` int(10) unsigned NOT NULL,
`code` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`quantity` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `stock_component_code_code_unique` (`component_code`,`code`),
KEY `stock_component_id_foreign` (`component_id`),
CONSTRAINT `stock_component_code_foreign` FOREIGN KEY (`component_code`) REFERENCES `components` (`code`) ON DELETE CASCADE
)
Obtengo
#1215 - Cannot add foreign key constraint
¿Que puedo hacer? No es tema de Laravel, El error lo obtengo en MySQL directamente.
RESUELTO Separando en dos Schema, la creación de la tabla y en otro la creación de indices. Así:
Schema::create('existencias', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('componente_code',20); // FK
$table->string('site',20); // Código de ubicacion
$table->string('idlabel',20)->default(''); // Identificador visual
$table->integer('cantidad')->unsigned()->default(1); // Cantidad
$table->integer('cargas')->unsigned()->default(0); // Ciclos de cargas (Baterías)
$table->json('info')->nullable(); // Información Extra (Baterías)
$table->char('estado', 1)->default("I"); // Tipo DIA - Descartado/Inactivo/Activo - Rojo/Amarill/Verde
//TS
$table->timestamps(); // Modified At - fecha de última modificación
});
Schema::table('existencias', function($table) {
$table->unique([
'componente_code',
'site',
'idlabel',
]);
$table->foreign('componente_code')
->references('code')->on('componentes')
->onDelete('cascade');
});
Gracias por vuestras respuestas
components
? – Shaz el 4 sep. 17 a las 20:18