SQL Associations

brandon·2023년 5월 31일
0

MySQL

목록 보기
3/4

https://chat.openai.com/share/5a954d95-26ca-47a8-928b-6add5662c288

0. SQL Associations

SQL에서 관계는 한 테이블의 데이터가 다른 테이블의 데이터와 어떻게 연결 되어 있는지 설명한다. 밑은 Sequelize를 사용한 각 관계들의 예시이다.

1. One-to-One Association

User이 있고 Profile 이 있다면 한 user 당 하나의 profile이 있으므로:

User.hasOne(Profile);
Profile.belongsTo(User);

이다.

2. One-to-Many Association

한 (one)user당 많은 (many)task를 할 수 있으므로:

User.hasMany(Task);
Task.belongsTo(User);

이다.

3. Many-to-Many Association:

한 user는 많은 project에 속할 수 있다. 또 한 project는 많은 user에 속할 수 있다.
이런 Many-to-Many Association 에서는 belongsToMany() 를 사용하여 junction table을 생성하여 parent table의 foreign key와 child table의 id를 저장하여 데이터를 추출할 수 있다.

const User = sequelize.define('User', {
  username: DataTypes.STRING,
});

const Project = sequelize.define('Project', {
  name: DataTypes.STRING,
});

const UserProject = sequelize.define('UserProject', {
  role: DataTypes.STRING,
});

User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });

여기서 through는 junction table로 사용할 table의 이름을 가리키며 만약 table이 전에 정의 되지 않았다면 through의 값을 이름으로 하는 junction table을 새로 만든다.

- Many-to-many 에서 Junction table value access하기

Junction table value를 access하여 값을 추출하거나 바꿀 수 있다.

Product.belongsToMany(Cart, {through: CartItem});
Cart.belongsToMany(Product, {through: CartItem});

라고 할떄, 한 cart에 있는 특정 id의 product를 찾기 위해서

cart.getProducts({where: {id: prodId}})
  .then(products => {
  	const product = products[0]
    return product.cartItem;
  })

처럼 product.cartItem으로 CartItem의 데이터를 추출 할 수 있다.

-Many-to-Many record 추가하기

똑같은 Cart & Product 관계에서

user.getCart()
	.then(cart => {
    	//product는 Product의 instance
    	return cart.addProduct(product)
    })

처럼 addProduct를 통하여 추가한다.
또는 addProducts로 여러개의 product가 있는 array를 넣어 여러개의 데이터를 한꺼번에 저장할 수 있다.

cart의 cartItem을 삭제 하려면 cart.product.cartItem.destroy()를 할 수 있다.

profile
everything happens for a reason

0개의 댓글