簡體   English   中英

laravel中如何設置主鍵本身為外鍵?

[英]How to set the primary key itself as a foreign key in laravel?

這聽起來很無聊,但我想知道我是否可以讓主鍵在 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”列的外鍵。

提前致謝。

這不是您對遷移文件所做的事情,而是您如何在模型本身中設置關系,老實說,我會嘗試避免使用相同的主鍵來表示兩個模型,而是在您的模型中添加另一列學生表名為$table->string('user_id', 30)->index(); 然后在您的 model class 中創建該關系,如下所示:

    public function user()
    {
        return $this->hasOne(User::class);
    }

雖然沒有必要,但您可以通過遷移添加外鍵約束。

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

你可以這樣做:

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');
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM