Answer the question
In order to leave comments, you need to log in
What is wrong with declaring a foreign key?
I categorically welcome!
I am making a page with an inventory of computers in the domain network in my laravel account, and when declaring the structure of tables and their relationships, I stumble over an error in foreign keys. What can be wrong?
The script that collects information about devices generates a unique id for each computer and enters the information into the database. Accordingly, in tables with disks, RAM and adapters (due to their possible set), rows should cling to the main one by this id.
public function up()
{
Schema::create('machines', function (Blueprint $table) {
// Структура
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->string('username')->nullable();
$table->string('domain')->nullable();
$table->string('model')->nullable();
$table->string('serial_number')->nullable();
$table->string('os')->nullable();
$table->string('cpu')->nullable();
// Отношения
$table->integer('machine_id')->unsigned()->index();
$table->foreign('machine_id')->references('m_id')->on('diskdrives')->onDelete('cascade');
//$table->foreign('machine_id')->references('m_id')->on('ram')->onDelete('cascade');
//$table->foreign('machine_id')->references('m_id')->on('net_adapters')->onDelete('cascade');
$table->timestamps();
});
}
public function up()
{
Schema::create('diskdrives', function (Blueprint $table) {
// Структура
$table->bigIncrements('id')->primary();
$table->integer('m_id')->nullable()->unsigned()->index();
$table->string('serial_number')->nullable();
$table->string('type')->nullable();
$table->string('model')->nullable();
$table->float('capacity')->nullable();
});
}
General error: 1005 Can't create table `inventory`.`machines` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `machines` add constraint `machines_machine_id_foreign` foreign key (`machine_id`) references `diskdrives` (`m_id`) on delete cascade)
Answer the question
In order to leave comments, you need to log in
Check in what order you run the migrations. Perhaps trying to create the `machines` table first when there is no `diskdrives` table yet
Is it possible to bind two more from the main file to the machine_id field using a foreign key?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question