如何在 Laravel 中定义这种关系?我尝试在 Laravel 中开发三个主键。但它不起作用。我该如何解决这个问题?
问问题
26 次
1 回答
0
这些键可以象征主键、外键、唯一列或索引。
一张表上不能有多个主键。
这是我尝试过的: 图
php .\artisan make:model Employee -m
php .\artisan make:model Title -m
php .\artisan make:model Salary -m
class CreateEmployeesTable extends Migration
{
public function up(): void
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('emp_no');
$table->string('first_name', 14);
$table->string('last_name', 16);
$table->date('birth_date');
$table->date('hire_date');
});
}
};
class CreateTitlesTable extends Migration
{
public function up(): void
{
Schema::create('titles', function (Blueprint $table) {
$table->unsignedBigInteger('emp_no');
$table->string('title', 50)->index();
$table->date('from_date')->index();
$table->foreign('emp_no')->references('emp_no')->on('employees');
});
}
};
class CreateSalariesTable extends Migration
{
public function up(): void
{
Schema::create('salaries', function (Blueprint $table) {
$table->unsignedBigInteger('emp_no');
$table->integer('salary');
$table->date('from_date')->index();
$table->foreign('emp_no')->references('emp_no')->on('employees');
});
}
};
编辑
假设多个键图标意味着一个复合键
class CreateEmployeesTable extends Migration
{
public function up(): void
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('emp_no');
$table->string('first_name', 14);
$table->string('last_name', 16);
$table->date('birth_date');
$table->date('hire_date');
});
}
};
class CreateTitlesTable extends Migration
{
public function up(): void
{
Schema::create('titles', function (Blueprint $table) {
$table->unsignedBigInteger('emp_no');
$table->string('title', 50);
$table->date('from_date');
$table->foreign('emp_no')->references('emp_no')->on('employees');
$table->primary(['emp_no', 'title', 'from_date']);
});
}
};
class CreateSalariesTable extends Migration
{
public function up(): void
{
Schema::create('salaries', function (Blueprint $table) {
$table->unsignedBigInteger('emp_no');
$table->integer('salary');
$table->date('from_date');
$table->foreign('emp_no')->references('emp_no')->on('employees');
$table->primary(['emp_no', 'from_date']);
});
}
};
于 2022-02-19T16:26:30.500 回答