前提
Next.js/TypeScript/GraphQL/Postgresを使って、店舗の1日の情報を記録する日報を作成しております。
Prismaを使って保存した値(total)を取得するようにしたいのですが処理がうまくいきません。
prisma.tsというファイルでの記載方法のアドバイスをいただきたいです。
実現したいこと
- dailyReportテーブルのtotalというカラムから値を取得したい
事前情報
modelの情報
- Company = 企業
- Shop = 店舗
- DailyReport = 日報
取得したい値
total = 人件費
該当のソースコード
schema.ts
1model Company { 2 id Int @id @default(autoincrement()) 3 name String @db.VarChar(255) 4 slug String @unique @db.VarChar(255) 5 createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0) 6 updatedAt DateTime? @updatedAt @map("updated_at") @db.Timestamp(0) 7 email String? @unique @db.VarChar(255) 8 shops Shop[] 9} 10 11model Shop { 12 id Int @id @default(autoincrement()) 13 name String @db.VarChar(255) 14 companyId Int @map("company_id") 15 shopId Int? @map("shop_id") 16 DailyReport DailyReport[] 17 @@unique([companyId, shopId], name: "shops_company_id_shop_id_unique") 18 @@map("shops") 19} 20 21model DailyReport { 22 id Int @id @default(autoincrement()) 23 shopId Int @map("shop_id") 24 date String? 25 total Int? @map("rent_cost") 26 createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0) 27 updatedAt DateTime? @default(now()) @map("updated_at") @db.Timestamp(0) 28 29 shop Shop @relation(fields: [shopId], references: [id]) 30 @@index([shopId], name: "monthly_reports_shop_id_index") 31 @@map("monthly_reports") 32} 33
prisma.ts
1async getDailyReports(companySlug: string, shopId: number, date: string): Promise<number> { 2 return ( 3 this.prisma.shop 4 .findFirst({ 5 where: { 6 shopId, 7 company: { 8 slug: companySlug, 9 }, 10 }, 11 }) 12 .then(shop => { 13 if (!shop) throw 'Shop not found'; 14 return ( 15 this.prisma.dailyReport 16 .findFirst({ 17 where: { 18 shopId: shop.id, 19 date: date, 20 }, 21 }) 22 .then(dailyReports => { 23 return dailyReports.map(dailyReport => { 24 const { total } = dailyReport; 25 return { 26 total, 27 }; 28 }); 29 }) 30 ); 31 }) 32 ); 33 }
試したこと
- prisma.tsのgetDailyReportsの引数で受け取った、companySlugと shopIdから取得したい店舗の情報を取得
- dailyReportから該当するshopIdとdateのレコードを取得
- 取得したレコードからtotalを返す
