2
Well, I’m using Typeorm in my TCC project. It’s something very simple, nothing very complex. I am using Postgresql to save the data, in the database I have only two tables, a call users and another call tank. What I need is that when a user registers a tank, in the table be recorded his id. But, the column "id_user" on the table tank, does not record the id user, the field is NULL. Below are the relations and routes that I have made.
User ts.
import { Entity, Column, PrimaryGeneratedColumn, OneToMany, JoinColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm'
import Tanque from './Tanque';
@Entity('usuario')
export default class User {
@PrimaryGeneratedColumn()
id: string;
@Column({
length: 50,
unique: true,
})
nome: string;
@Column({
length: 50,
})
cidade: string;
@CreateDateColumn({ name: 'created_At' })
createdAt: Date;
@UpdateDateColumn({ name: 'update_At' })
updateAt: Date;
@OneToMany(() => Tanque, tanque => tanque.user, {
cascade: ['insert', 'update']
})
@JoinColumn()
tanque: Tanque[];
}
Tanque.ts
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn, UpdateDateColumn, JoinColumn } from 'typeorm'
import User from './User';
@Entity('tanque')
export default class Tanque {
@PrimaryGeneratedColumn()
id: string;
@Column({
length: 50,
unique: true
})
nome_tanque: string;
@Column()
altura: string;
@Column()
largura: string;
@Column()
comprimento: string;
@Column()
phAgua: string;
@Column()
quantPeixe: string;
@CreateDateColumn({ name: 'created_At' })
createdAt: Date;
@UpdateDateColumn({ name: 'update_At' })
updateAt: Date;
@ManyToOne(() => User, user => user.tanque)
@JoinColumn()
user: User;
}
Routes:
usuario.routests.
import { Router } from 'express';
import { getRepository } from 'typeorm';
import { validate } from 'class-validator'
import Usuario from '../models/User';
const usuarioRouter = Router();
usuarioRouter.post('/', async (request, response) => {
try {
const repo = getRepository(Usuario);
const { id, nome, cidade } = request.body;
const user = repo.create({
id,
nome,
cidade
});
const erros = await validate(user);
if (erros.length === 0) {
const res = await repo.save(user);
return response.status(201).json(res);
}
return response.status(400).send();
} catch (err) {
console.log('err.message :>> ', err.message);
return response.status(400).send();
}
});
export default usuarioRouter;
tank.routests.
import { Router } from 'express';
import { getRepository } from 'typeorm';
import Tanque from '../models/Tanque';
const classRouter = Router();
classRouter.post('/', async (request, response) => {
try {
const repo = getRepository(Tanque);
const res = await repo.save(request.body);
return response.status(201).json(res)
} catch (err) {
console.log('Mensagem de erro :>> ', err.message);
return response.status(400).send();
}
});
export default classRouter;
The same thing happened to me, waiting for an answer
– Edward Ramos