inflearn logo
강의

Khóa học

Chia sẻ kiến thức

[CodeCamp] Khóa học backend cô đặc được tạo ra từ bootcamp

1:1 관계 등록 API 질문입니다.

Đã giải quyết

331

LI

7 câu hỏi đã được viết

0

 

  //18-03의 방법 2. 상품과 상품 거래위치를 같이 등록하는 경우

  async create({ createProductInput }) {
    const { productSaleslocation, ...product } = createProductInput;
    console.log(
      '어떻게 받아오는지 createProductInput:::::::::찍어보자 ',
      createProductInput,
    );

    console.log(
      '서비스단에서 productSaleslocation::::::::',
      productSaleslocation,
    );
    // console.log('서비스단에서...product:::::::::::::::', ...product);

    const result = await this.productSaleslocationRepository.save({
      ...productSaleslocation,
      //
    });
    console.log('서비스단에서 result:::::', result);

    const result2 = await this.productRepository.save({
      ...product,
      productSaleslocationId: result.id,
    });

    console.log('서비스단에서 result2:::::', result2);

    return result2;
  }

 

위를 grpahql 에서 데이터를 전송해보면,

터미널창에서

아래와 같이 나옵니다.

 

어떻게 받아오는지 createProductInput:::::::::찍어보자  [Object: null prototype] {
  name: '마우스',
  description: '참좋은마우스',
  price: 2000,
  productSaleslocation: [Object: null prototype] {
    address: '구로',
    addressDetail: '구로역',
    lat: 1,
    lng: 1,
    meetingTime: 2022-10-30T00:00:00.000Z
  }
}
서비스단에서 productSaleslocation:::::::: [Object: null prototype] {
  address: '구로',
  addressDetail: '구로역',
  lat: 1,
  lng: 1,
  meetingTime: 2022-10-30T00:00:00.000Z
}
query: START TRANSACTION
query: INSERT INTO `product_saleslocation`(`id`, `address`, `addressDetail`, `lat`, `lng`, `meetingTime`) VALUES (?, ?, ?, ?, ?, ?) -- PARAMETERS: ["f6bc848d-42ff-42c5-a454-39e8a9106dac","구로","구로역",1,1,"2022-10-30T00:00:00.000Z"]
query: COMMIT
서비스단에서 result::::: {
  address: '구로',
  addressDetail: '구로역',
  lat: 1,
  lng: 1,
  meetingTime: 2022-10-30T00:00:00.000Z,
  id: 'f6bc848d-42ff-42c5-a454-39e8a9106dac'
}
query: START TRANSACTION
query: INSERT INTO `product`(`id`, `name`, `description`, `price`, `isSoldout`, `deletedAt`, `productSaleslocationId`, `productCategoryId`, `userId`) VALUES (?, ?, ?, ?, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) -- PARAMETERS: ["a09e9c56-4b45-420d-98ec-c075da6014e0","마우스","참좋은마우스",2000]
query: SELECT `Product`.`id` AS `Product_id`, `Product`.`isSoldout` AS `Product_isSoldout`, `Product`.`deletedAt` AS `Product_deletedAt` FROM `product` `Product` WHERE ( `Product`.`id` = ? ) AND ( `Product`.`deletedAt` IS NULL ) -- PARAMETERS: ["a09e9c56-4b45-420d-98ec-c075da6014e0"]
query: COMMIT
서비스단에서 result2::::: {
  name: '마우스',
  description: '참좋은마우스',
  price: 2000,
  productSaleslocationId: 'f6bc848d-42ff-42c5-a454-39e8a9106dac',
  deletedAt: null,
  id: 'a09e9c56-4b45-420d-98ec-c075da6014e0',
  isSoldout: false
}
어떻게 받아오는지 createProductInput:::::::::찍어보자  [Object: null prototype] {
  name: '마우스',
  description: '참좋은마우스1',
  price: 2000,
  productSaleslocation: [Object: null prototype] {
    address: '구로',
    addressDetail: '구로역',
    lat: 1,
    lng: 1,
    meetingTime: 2022-10-30T00:00:00.000Z
  }
}
서비스단에서 productSaleslocation:::::::: [Object: null prototype] {
  address: '구로',
  addressDetail: '구로역',
  lat: 1,
  lng: 1,
  meetingTime: 2022-10-30T00:00:00.000Z
}
query: START TRANSACTION
query: INSERT INTO `product_saleslocation`(`id`, `address`, `addressDetail`, `lat`, `lng`, `meetingTime`) VALUES (?, ?, ?, ?, ?, ?) -- PARAMETERS: ["33a4c94a-886d-4f76-9226-a363afc4b7e4","구로","구로역",1,1,"2022-10-30T00:00:00.000Z"]
query: COMMIT
서비스단에서 result::::: {
  address: '구로',
  addressDetail: '구로역',
  lat: 1,
  lng: 1,
  meetingTime: 2022-10-30T00:00:00.000Z,
  id: '33a4c94a-886d-4f76-9226-a363afc4b7e4'
}
query: START TRANSACTION
query: INSERT INTO `product`(`id`, `name`, `description`, `price`, `isSoldout`, `deletedAt`, `productSaleslocationId`, `productCategoryId`, `userId`) VALUES (?, ?, ?, ?, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) -- PARAMETERS: ["a97bb588-3074-4f1b-abaf-a9d244616dd3","마우스","참좋은마우스1",2000]
query: SELECT `Product`.`id` AS `Product_id`, `Product`.`isSoldout` AS `Product_isSoldout`, `Product`.`deletedAt` AS `Product_deletedAt` FROM `product` `Product` WHERE ( `Product`.`id` = ? ) AND ( `Product`.`deletedAt` IS NULL ) -- PARAMETERS: ["a97bb588-3074-4f1b-abaf-a9d244616dd3"]
query: COMMIT
서비스단에서 result2::::: {
  name: '마우스',
  description: '참좋은마우스1',
  price: 2000,
  productSaleslocationId: '33a4c94a-886d-4f76-9226-a363afc4b7e4',
  deletedAt: null,
  id: 'a97bb588-3074-4f1b-abaf-a9d244616dd3',
  isSoldout: false
}

 

강의에서 설명해주신 코드는


    const result2 = await this.productRepository.save({
      ...product,
      productSaleslocation: result,
    });

    console.log('서비스단에서 result2:::::', result2);

    return result2;
  }

...product를 하면 product 테이블에 product와 관련된 데이터(name, description, price) 가 DB 테이블에 들어가는 것은 이해가 되었는데,

productSaleslocation: result 라고 하면, DB에

lnt, lng, meetingtime, address, adressDetail까지 전부 들어가는 게 아닌가요?

 

왜 DB를 확인해보면, productSaleslocation의 id 값만 productSaleslocationId 컬럼에 들어가게 되는 것인가요?

 

그래서 product 테이블에 productSalesloactionId 라는 컬럼이 있어서 아래와 같이 result2 코드를 작성해보았습니다.

    const result2 = await this.productRepository.save({
      ...product,
      productSaleslocationId: result.id,
    });

이렇게 코드를 작성하면,

상품테이블에 productSaleslocationId 컬럼이 있으니,

productSaleslocationId : result.id 를 해줘서

DB에 productSaleslocationId 값을 넣을 수 있는게 왜 아닌지 이해가 가지 않습니다.

왜 productSaleslocationId : result.id 라고 하면 터미널창에는 찍히지만,

DB에 아무것도 들어가지 않는 것일까요?

오히려 productSaleslocation: result 라고 하면,

productSaleslocation의 lnt, lng, meetingtime, address, adressDetail 은 하나도 들어가지 않고, 어떠한 에러가 발생하지 않고, productSaleslocation의 id값만 외래키로 DB에 잘 들어가게 되는것일까요?

 

node.js express tdd nodejs rest-api docker javascript nestjs NestJS

Câu trả lời 1

0

angie

안녕하세요. LI님

해당 로직은 상품과 상품거래위치를 함께 등록하기 위해 만들어진 로직입니다.
result에서 상품거래위치를 할당하여 데이터가 저장되면 그 결과값을 다시 한번 상품 등록시에 객체 값에 할당하여 함께 저장하게 됩니다.
이 때 각 데이터들은 컬럼값을 가진 테이블에 저장되게 되며, Dbeaver로 이를 확인 시, product 테이블에서 product 테이블이 가지고 있는 데이터의 값들과 이와 연결되어 있는 외래키의 값을 확인할 수 있습니다.
productSaleslocation의 데이터는 해당 테이블에서 데이터를 확인할 수 있으며, 이 데이터가 가지는 id 값으로 연결된 product 테이블에서 productSaleslocationId를 참조하여 이를 확인할 수 있게 됩니다.

로직에 이상이 없다면 이미 저장된 데이터들이 새로 동기화되지 않아, 데이터가 제대로 저장되지 않을 수 있으므로 해당 로직에 연관된 데이터들을 drop 또는 새로운 데이터베이스로 실습을 진행해 보시길 바랍니다. 또한 동기화를 위해 dist 폴더 삭제 후 서버를 재실행 해 보시길 바랍니다. 감사합니다.

그래프 ql 문서 사용할때 느낌표 남는거 어떻게 없애나요?

0

80

2

강의 전체 소스 코드를 받고싶습니다.

0

74

2

fontawesome 사용 문의

0

75

2

소스 코드 부탁드립니다~

0

84

2

깃 레포지터리 소스

0

78

2

커리큘럼12.css 정렬 에 나오는 과제 정답알고싶어요

0

71

2

10-01 Entity TypeOrmModule.forRoot 에 entities

0

83

3

강의 버전관련 문의입니다

0

101

2

Ubuntu 설치 관련

0

59

1

schema.gql 질문 드립니다.

0

49

1

서버 재실행시 Many to Many

0

100

3

input 관련 문의

0

89

2

Rest API 보다는 graphql이 주된 내용인데

0

130

2

강의 전체 소스코드 받을수있을까요?

0

153

1

도커볼륨 마운트 관련

0

125

2

findOne 타입스크립트오류

0

107

1

http => htrtps 호출 인증서 신뢰 오류

0

347

1

self-signed certificate in certificate chain 에러 발생

0

408

1

mongoose 설치 오류

0

140

1

특정 API, 특정 IP 허용 (단일경로에 CORS 활성화)

0

279

2

08-06

0

174

3

구조랑 패턴 관련해서 질문

0

121

2

mydocker

0

125

2

coolsms statuscode 2000 인데 전송안돼는 경우 확인.

0

153

1