這聽起來很蠢,但我想知道我是否可以讓主鍵在 Laravel 中作為外鍵作業,而且我是 Laravel 的新手。
因此,我有兩個遷移“用戶”和“學生”,如下所示: 用戶:
Schema::create('users', function (Blueprint $table) {
$table->string('uniqueId', 30)->primary();
$table->text('password');
$table->string('userType');
$table->timestamps();
});
和學生:
Schema::create('students', function (Blueprint $table) {
$table->string('uniqueId', 30)->primary();
$table->text('name');
$table->text('fName');
$table->text('mName');
$table->text('addr');
$table->string('image');
$table->integer('class');
$table->integer('roll');
$table->string('year');
$table->timestamps();
});
所以,我想要的只是Student (uniqueId)中的主鍵也可以用作參考User表中的“uniqueId”列的外鍵。
提前致謝。
uj5u.com熱心網友回復:
這不是你用遷移檔案做的事情,而是你如何在你的模型中建立關系,老實說,我會盡量避免使用相同的主鍵來表示兩個模型,而是將另一列添加到你的學生表呼叫$table->string('user_id', 30)->index();然后在您的模型類中創建該關系,如下所示:
public function user()
{
return $this->hasOne(User::class);
}
uj5u.com熱心網友回復:
雖然不是必需的,但您可以通過遷移添加外鍵約束。
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
uj5u.com熱心網友回復:
你可以這樣做:
if (!Schema::hasTable('users')) {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->text('password');
$table->string('userType');
$table->timestamps();
});
}
if (!Schema::hasTable('students')) {
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
$table->text('fName');
$table->text('mName');
$table->text('addr');
$table->string('image');
$table->integer('class');
$table->integer('roll');
$table->string('year');
$table->timestamps();
$table->foreign('user_id', 'fk_users_user_id')
->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('cascade');
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376339.html
上一篇:sqoop作業中臨時rootdir和bindir的區別
下一篇:Laravel路由組和中間件
