Home > Blockchain >  Does laravel can create relationship between tables in sql database server?
Does laravel can create relationship between tables in sql database server?

Time:01-19

I have a laravel project working fine but i can't see relationship in sql server.(for which i am using xampp).

I expect the foreign-id in laravel is the foreign id in actual table. It is working fine in laravel, i expect it to work in actual database server also.

This is my model, Student Model and migration:

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

User Model and migration:

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

In designer view, there is no link between students.user_id, and users.id:

designer view

CodePudding user response:

There are many better guides out there that explains this, so I will try to keep this simple, there are 2 things you need to understand about how database relationships work within laravel:

1- You can connect your database tables to be related to each other, this has many benefits where you can cascade delete data as an example.

You are currently not telling mysql which tables are being connected, you can see a better way to do this from the following stackoverflow: laravel migration best way to add foreign key

2- You can connect your database tables using Models, this will not show up anywhere in MYSQL designer, because this is mainly code base, which is enough to handle all of the data processing between relationships.

This part you already did.

CodePudding user response:

you need to define the foreign key constraints explicitly in your migration file.

You can use the foreign() method on the foreign key columns to define the foreign key constraints. For example, to create a foreign key constraint on the "user_id" and "course_id" columns

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();
});
  • Related