Advertisement

Penjelasan Lengkap Relasi Model Database di Sequelize

 


Sequelize adalah ORM (Object-Relational Mapping) untuk Node.js yang digunakan untuk berinteraksi dengan database SQL seperti MySQL, PostgreSQL, SQLite, dan MSSQL. Salah satu fitur penting dalam Sequelize adalah kemampuannya untuk mendefinisikan relasi antar model.

1. Jenis-Jenis Relasi dalam Sequelize

Sequelize mendukung beberapa jenis relasi dalam database:

  1. One-to-One (1:1) → Satu entitas hanya memiliki satu entitas lain yang terkait.
  2. One-to-Many (1:M) → Satu entitas bisa memiliki banyak entitas terkait.
  3. Many-to-Many (M:N) → Banyak entitas memiliki hubungan dengan banyak entitas lainnya.

2. Implementasi Relasi dalam Sequelize

a) One-to-One Relationship

Dalam relasi 1:1, satu baris dalam tabel A hanya terkait dengan satu baris dalam tabel B.

Contoh Kasus

Misalkan kita punya dua tabel:

  • User (Menyimpan informasi pengguna)
  • Profile (Menyimpan detail tambahan pengguna)

Implementasi di Sequelize

const { Sequelize, DataTypes } = require("sequelize");
const sequelize = new Sequelize("database", "username", "password", {
  dialect: "mysql",
});

// Definisi Model
const User = sequelize.define("User", {
  name: { type: DataTypes.STRING, allowNull: false },
});

const Profile = sequelize.define("Profile", {
  bio: { type: DataTypes.STRING },
});

// Relasi One-to-One
User.hasOne(Profile, {
  foreignKey: "userId",
  as: "profile",
});
Profile.belongsTo(User, {
  foreignKey: "userId",
  as: "user",
});

// Sinkronisasi
sequelize.sync({ force: true }).then(() => console.log("Database synced"));

Penjelasan

  • User.hasOne(Profile) → Menunjukkan bahwa satu user hanya memiliki satu profile.
  • Profile.belongsTo(User) → Menandakan bahwa profile tersebut milik satu user tertentu.
  • foreignKey: "userId" → Menentukan kolom kunci asing (userId) di tabel Profile.

b) One-to-Many Relationship

Dalam relasi 1:M, satu entitas di tabel A bisa memiliki banyak entitas di tabel B.

Contoh Kasus

Misalkan kita memiliki dua tabel:

  • User (Pengguna aplikasi)
  • Post (Postingan yang dibuat pengguna)

Implementasi di Sequelize

const Post = sequelize.define("Post", {
  title: { type: DataTypes.STRING, allowNull: false },
  content: { type: DataTypes.TEXT },
});

// Relasi One-to-Many
User.hasMany(Post, {
  foreignKey: "userId",
  as: "posts",
});
Post.belongsTo(User, {
  foreignKey: "userId",
  as: "author",
});

Penjelasan

  • User.hasMany(Post) → Menunjukkan bahwa satu user bisa memiliki banyak post.
  • Post.belongsTo(User) → Menunjukkan bahwa setiap post dimiliki oleh satu user.
  • foreignKey: "userId" → Menambahkan kolom userId pada tabel Post untuk menghubungkannya ke User.

c) Many-to-Many Relationship

Dalam relasi M:N, banyak entitas di tabel A dapat terkait dengan banyak entitas di tabel B.

Contoh Kasus

Misalkan kita memiliki dua tabel:

  • Student (Mahasiswa)
  • Course (Mata kuliah)

Karena satu mahasiswa bisa mengambil banyak mata kuliah dan satu mata kuliah bisa diikuti oleh banyak mahasiswa, maka kita perlu tabel perantara.

Implementasi di Sequelize

const Student = sequelize.define("Student", {
  name: { type: DataTypes.STRING, allowNull: false },
});

const Course = sequelize.define("Course", {
  title: { type: DataTypes.STRING, allowNull: false },
});

// Relasi Many-to-Many
Student.belongsToMany(Course, { through: "StudentCourses" });
Course.belongsToMany(Student, { through: "StudentCourses" });

Penjelasan

  • Student.belongsToMany(Course, { through: "StudentCourses" }) → Sequelize akan membuat tabel perantara (StudentCourses).
  • Course.belongsToMany(Student, { through: "StudentCourses" }) → Hubungan dua arah, satu mahasiswa bisa memiliki banyak mata kuliah dan sebaliknya.

3. Menggunakan Relasi dalam Query

Setelah mendefinisikan relasi, kita bisa menggunakannya dalam query menggunakan Sequelize.

a) Mengambil Data dengan Relasi (Include)

const getUsersWithProfile = async () => {
  const users = await User.findAll({
    include: [{ model: Profile, as: "profile" }],
  });
  console.log(JSON.stringify(users, null, 2));
};
getUsersWithProfile();

b) Menyimpan Data dengan Relasi

const createUserWithProfile = async () => {
  const user = await User.create(
    {
      name: "John Doe",
      profile: { bio: "Web Developer" },
    },
    { include: [{ model: Profile, as: "profile" }] }
  );
  console.log("User Created:", user.toJSON());
};
createUserWithProfile();

Kesimpulan

  • One-to-One (hasOne - belongsTo) → Contoh: User & Profile
  • One-to-Many (hasMany - belongsTo) → Contoh: User & Post
  • Many-to-Many (belongsToMany - belongsToMany) → Contoh: Student & Course
  • Gunakan include dalam query untuk mengambil data dengan relasi.

Dengan memahami konsep ini, kamu bisa membangun aplikasi berbasis database yang lebih kompleks menggunakan Sequelize! 

 

Post a Comment

0 Comments