簡體   English   中英

laravel是否可以在sql數據庫服務器中創建表之間的關系?

[英]Does laravel can create relationship between tables in sql database server?

我有一個 laravel 項目工作正常,但我看不到 sql 服務器中的關系。(我正在使用 xampp)。

我希望laravel中的foreign-id是實際表中的foreign id。 它在 laravel 中運行良好,我希望它也能在實際的數據庫服務器中運行。

這是我的model,學生Model和遷移:

public function user() {
    return $this->belongsTo(User::class);
}
Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string("username")->unique();
    $table->foreignId("user_id");
    $table->foreignId("course_id");
    $table->bigInteger("class_roll");
    $table->integer("year");
    $table->integer("semester")->nullable();
    $table->timestamps();
});

用戶Model及遷移:

public function student()
{
    return $this->hasOne(Student::class);
}
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->boolean('is_active');
    $table->enum('role', ['admin','instructor','student']);
    $table->string("fullname");
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

在設計器視圖中,students.user_id 和 users.id 之間沒有鏈接:

設計師觀點

您需要在遷移文件中明確定義外鍵約束。

您可以在外鍵列上使用 foreign() 方法來定義外鍵約束。 例如,在“user_id”和“course_id”列上創建外鍵約束

Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string("username")->unique();
    $table->foreignId("user_id")->constrained()->on('users');
    $table->foreignId("course_id")->constrained()->on('courses');
    $table->bigInteger("class_roll");
    $table->integer("year");
    $table->integer("semester")->nullable();
    $table->timestamps();
});

有許多更好的指南可以解釋這一點,所以我會盡量保持簡單,關於數據庫關系如何在 laravel 中工作,您需要了解兩件事:

1-您可以連接您的數據庫表以相互關聯,這有很多好處,例如您可以級聯刪除數據。

您目前沒有告訴 mysql 正在連接哪些表,您可以從以下 stackoverflow 中看到更好的方法: laravel migration best way to add foreign key

2-您可以使用模型連接您的數據庫表,這不會顯示在 MYSQL 設計器的任何地方,因為這主要是代碼庫,足以處理關系之間的所有數據處理。

這部分你已經做過了。

暫無
暫無

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

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