#OneToOne is being ManyToOne

165 messages · Page 1 of 1 (latest)

rancid pike
#

Think your missing stuff

glacial bluff
glacial bluff
rancid pike
#

One driver can have many vehicles

glacial bluff
# rancid pike One driver can have many vehicles

i dont want it to be many to many.... there is another entity down the road that will need a one to one too i need to have it as one to one as one student can use only one vehicle the "orginisation" is interested to track every student mode of transportation i have attached how i want it to look like

#

please note that one member use one vehicle and one driver use one vehicle

rancid pike
#

You'll need a composite primary key with driverid and memberid in the vehicle table

#

Otherwise it'll be one to many

glacial bluff
rancid pike
#

You could make driverid and memberid a foreign key and driverid as the primary

undone reef
#

check your Vehicle entity. If you want a one to one relationship with Driver, you gotta change the decorator to @OneToOne(() => Driver) and don’t forget @JoinColumn() that's what tells TypeORM which side owns the relationship. Otherwise, it defaults to many-to-one behavior.

glacial bluff
undone reef
#

// In Vehicle entity
@OneToOne(() => Driver, (driver) => driver.vehicle)
@JoinColumn()
vehicleDriverID: Driver;

// In Driver entity
@OneToOne(() => Vehicle, (vehicle) => vehicle.vehicleDriverID)
vehicle: Vehicle;

glacial bluff
glacial bluff
glacial bluff
undone reef
#

can u pass the entire vehicle entity pls

glacial bluff
#

sure

undone reef
#

like the code

glacial bluff
#
import {Column, Entity, JoinColumn, OneToOne, PrimaryColumn} from "typeorm";
import {Driver} from "../driver/driver.entity";

@Entity()
export class Vehicle {
    @PrimaryColumn()
    vehicleRegNum: number;

    @OneToOne(() => Driver)
    @JoinColumn()
    vehicleDriverID: Driver;

    @Column()
    vehicleBrand: string;

    @Column()
    vehicleModel: string;

    @Column()
    vehicleType: number;

    @Column()
    vehicleCapacity: number;
}
glacial bluff
#

create vehicle dto

import {Driver} from "../../driver/driver.entity";


export class createVehicleDTO {
    vehicleRegNum: number;
    vehicleDriverID: Driver;
    vehicleBrand: string;
    vehicleModel: string;
    vehicleType: number;
    vehicleCapacity: number;
}
#

and vehicle service

import {updateVehicleDTO} from "./dto/update-vehicle.dto"
import {Vehicle} from "./vehicle.entity";
import {Driver} from "../driver/driver.entity"
import {driverService} from "../driver/driver.service"


@Injectable()
export class vehicleService {
    constructor(
        @InjectRepository(Vehicle)
        private readonly vehicleRepository: Repository<Vehicle>,
        private readonly driverService: driverService
    ) {
    }

    @InjectRepository(Driver)
    createVehicle(createVehicleDTO: createVehicleDTO): Promise<Vehicle> {
        const vehicle = new Vehicle();
        vehicle.vehicleRegNum = createVehicleDTO.vehicleRegNum;
        vehicle.vehicleBrand = createVehicleDTO.vehicleBrand;
        vehicle.vehicleModel = createVehicleDTO.vehicleModel;
        vehicle.vehicleType = createVehicleDTO.vehicleType;
        vehicle.vehicleCapacity = createVehicleDTO.vehicleCapacity;

        vehicle.vehicleDriverID = createVehicleDTO.vehicleDriverID;

        return this.vehicleRepository.save(vehicle);
    }
//rest of the services
}
undone reef
#

try this

glacial bluff
undone reef
#

@Column({ unique: true })

glacial bluff
undone reef
#

man just try it

glacial bluff
undone reef
#

in the vehicle entity above the driver field

#

@Entity()
export class Vehicle {
@PrimaryColumn()
vehicleRegNum: number;

@OneToOne(() => Driver)
@JoinColumn()
@Column({ unique: true }) // Ensure that each driver can only be linked to one vehicle
vehicleDriverID: Driver;

@Column()
vehicleBrand: string;

@Column()
vehicleModel: string;

@Column()
vehicleType: number;

@Column()
vehicleCapacity: number;

}

glacial bluff
#

ok ill run this code one sec

#

now it spits an error

undone reef
#

okay nvm then i'm sorry

glacial bluff
undone reef
#

okay so in the dto instead of passing the whole driver object

#

why not pass the driver id

glacial bluff
#

use driverservice to dind the approriate id?

undone reef
#

`// In vehicle.entity.ts
import {Column, Entity, JoinColumn, OneToOne, PrimaryColumn} from "typeorm";
import {Driver} from "../driver/driver.entity";

@Entity()
export class Vehicle {
@PrimaryColumn()
vehicleRegNum: number;

// Change property name to better reflect what it is
@OneToOne(() => Driver, (driver) => driver.vehicle, { nullable: true })
@JoinColumn()
driver: Driver;

@Column()
vehicleBrand: string;

@Column()
vehicleModel: string;

@Column()
vehicleType: number;

@Column()
vehicleCapacity: number;

}`

#

export class createVehicleDTO { vehicleRegNum: number; driverId: number; // Change to just store the ID vehicleBrand: string; vehicleModel: string; vehicleType: number; vehicleCapacity: number; }

#

this is the entity and dto

#

then u update the service

#

`@Injectable()
export class vehicleService {
constructor(
@InjectRepository(Vehicle)
private readonly vehicleRepository: Repository<Vehicle>,
@InjectRepository(Driver) // Fix placement
private readonly driverRepository: Repository<Driver>,
private readonly driverService: driverService
) {}

async createVehicle(createVehicleDTO: createVehicleDTO): Promise<Vehicle> {
    const vehicle = new Vehicle();
    vehicle.vehicleRegNum = createVehicleDTO.vehicleRegNum;
    vehicle.vehicleBrand = createVehicleDTO.vehicleBrand;
    vehicle.vehicleModel = createVehicleDTO.vehicleModel;
    vehicle.vehicleType = createVehicleDTO.vehicleType;
    vehicle.vehicleCapacity = createVehicleDTO.vehicleCapacity;
    
    // Find the driver by ID instead of directly assigning
    if (createVehicleDTO.driverId) {
        const driver = await this.driverRepository.findOne(createVehicleDTO.driverId);
        vehicle.driver = driver;
    }
    
    return this.vehicleRepository.save(vehicle);
}
// Rest of the services

}`

glacial bluff
#

hold up

glacial bluff
#

why is this answer so counter intuitive i have to find the id to make the relation isnt there an easier approach to do it?

undone reef
#

yes but you take the driver id from dto and u get the whole driver object in the service and u assign it to the class entity

undone reef
glacial bluff
undone reef
glacial bluff
undone reef
#

idk man i give up lmao

#

best of luck

glacial bluff
#

have a good one

undone reef
#

i never coded with next js before , i only use java for backend and no sql database

#

it removes the relationships headache

glacial bluff
undone reef
#

mfs want me to code in C

ancient talon
#

Have you made sure both the Vehicle and Driver entities have @OneToOne relationships to each other, and that the Driver entity doesn't have any @OneToMany or @ManyToMany relationships?

glacial bluff
#

i dont want any foreign keys to driver entity*

glacial bluff
#

driver without any foreign keys

#

the foreign key of the driver in the vehicle

glacial bluff
ancient talon
#

in that case, to get that strict one-to-one thing working without foreign keys messing up your Driver setup, you'll want the Vehicle to "own" the relationship by holding the foreign key to the Driver. Think of it as the Vehicle knowing who's driving it, and similarly, have the Member entity "own" a relationship with a Vehicle in a similar way.

glacial bluff
ancient talon
#

🙏 I just woke up too haha, Let's see if im rusty or not

glacial bluff
#

if you need to take your time it is okay

glacial bluff
#

(although i already did but eh why not paste it again)

glacial bluff
# ancient talon Sure

so driver.entity.ts

import {Column, Entity, PrimaryColumn} from "typeorm";

@Entity()
export class Driver {
    @PrimaryColumn()
    driverID: number;

    @Column()
    driverName: string;

    @Column()
    driverNumber: number;

    @Column()
    driverRegion: string;
}

create-driver.dto.ts

export class createDriverDTO {
    driverID: number;
    driverName: string;
    driverNumber: number;
    driverRegion: string;
}

driver.service.ts

import {Repository} from "typeorm";
import {Injectable, NotFoundException} from "@nestjs/common";
import {InjectRepository} from "@nestjs/typeorm";

import {createDriverDTO} from "./dto/create-driver.dto";
import {Driver} from "./driver.entity";
import {updateDriverDTO} from "./dto/update-driver.dto";


@Injectable()
export class driverService {
    constructor(
        @InjectRepository(Driver)
        private readonly driverRepository: Repository<Driver>,
    ) {
    }

    createDriver(createDriverDTO: createDriverDTO): Promise<Driver> {
        const driver = new Driver();
        driver.driverID = createDriverDTO.driverID;
        driver.driverName = createDriverDTO.driverName;
        driver.driverNumber = createDriverDTO.driverNumber;
        driver.driverRegion = createDriverDTO.driverRegion;

        return this.driverRepository.save(driver);
    }
//rest of the servuces
}
#

thats for driver

#

now for the vehicle

#

vehicle.entity.ts

import {Column, Entity, JoinColumn, OneToOne, PrimaryColumn} from "typeorm";
import {Driver} from "../driver/driver.entity";

@Entity()
export class Vehicle {
    @PrimaryColumn()
    vehicleRegNum: number;

    @OneToOne(() => Driver)
    @JoinColumn()
    vehicleDriverID: Driver;

    @Column()
    vehicleBrand: string;

    @Column()
    vehicleModel: string;

    @Column()
    vehicleType: number;

    @Column()
    vehicleCapacity: number;
}
ancient talon
#

is that all?

glacial bluff
#

create-vehicle.dto.ts

import {Driver} from "typeorm";

export class createVehicleDTO {
    vehicleRegNum: number;
    vehicleDriverID: Driver;
    vehicleBrand: string;
    vehicleModel: string;
    vehicleType: number;
    vehicleCapacity: number;
}
#

i still have the driver service

#

idk i messed my files im trying to fix it

#

atleast how it was

ancient talon
#

Alright, update VehicleService to fetch the Driver entity by ID and assign it to vehicleDriverID before saving the Vehicle, this will ensure the one-to-one relationship is correctly linked.

glacial bluff
glacial bluff
glacial bluff
ancient talon
#

Yeah, you could instead of fetching the Driver entity, you could perhaps directly assign the driverID to a vehicleDriverID column in the Vehicle entity and establish the relationship through that; that way, TypeORM handles the linking under the hood.

glacial bluff
#

i mean look at my DB

ancient talon
#

it should be

glacial bluff
ancient talon
# glacial bluff so how i should proceed from here
  • Modify Vehicle entity: Remove the direct relationship/foreign key to the Driver entity.
  • Instead, add driverDriverId (matching your Driver's driverId) to the vehicle entity.
  • TypeORM: Define a relation in Vehicle using driverDriverId to connect to your Driver entity.
glacial bluff
#

just one thing i fixed the create vehicle and service i had some bad modifications
create vehicle

import {Driver} from "../../driver/driver.entity";

export class createVehicleDTO {
    vehicleRegNum: number;
    vehicleDriverID: Driver;
    vehicleBrand: string;
    vehicleModel: string;
    vehicleType: number;
    vehicleCapacity: number;
}

and vehicle service

    @InjectRepository(Driver)
    createVehicle(createVehicleDTO: createVehicleDTO): Promise<Vehicle> {
        const vehicle = new Vehicle();
        vehicle.vehicleRegNum = createVehicleDTO.vehicleRegNum;
        vehicle.vehicleBrand = createVehicleDTO.vehicleBrand;
        vehicle.vehicleModel = createVehicleDTO.vehicleModel;
        vehicle.vehicleType = createVehicleDTO.vehicleType;
        vehicle.vehicleCapacity = createVehicleDTO.vehicleCapacity;

        vehicle.vehicleDriverID = createVehicleDTO.vehicleDriverID;

        return this.vehicleRepository.save(vehicle);
    }
glacial bluff
ancient talon
ancient talon
glacial bluff
#

thats what i am doing now

glacial bluff
glacial bluff
ancient talon
glacial bluff
ancient talon
glacial bluff
ancient talon
#

oooohhh

#

😭 omd this is really stressing fr

glacial bluff
#

just to end up in the same place

#

a many to one when it should be 1 to 1

#

i still have to do the front end 🪦

ancient talon
#

Something like this?

// Vehicle entity
@ManyToOne(() => Driver, (driver) => driver.vehicles)
@JoinColumn({ name: 'driver_driverID' })
driver: Driver;

// Driver entity
@OneToMany(() => Vehicle, (vehicle) => vehicle.driver)
vehicles: Vehicle[];

Make sure the column names match your actual database columns (driver_driverID).

glacial bluff
ancient talon
glacial bluff
ancient talon
glacial bluff
#

bcs i want to avoid a situation like this

ancient talon
glacial bluff
glacial bluff
#

but it was along the line of what you did

ancient talon
# glacial bluff in vehicle entity
// Bi-directional
class Driver {
  vehicle: Vehicle; // <-- make sure this is there
}

// Uni-directional - access driver from vehicle
const theDriversVehicle = vehicle.driver;```
#

oh you fixed it already?

#

haha beat it to me :)))

glacial bluff
ancient talon
#

ahhh yea

glacial bluff
#

WHY

#

WHY WHY WHY

ancient talon
#

💀 okay i give up now-

#

Someone else pls help the dude, my heads hurting too 😭 ! we mut suffer together

glacial bluff
ancient talon
#

I wish i would be more help but honstly this simple thing is just sooo confusing

glacial bluff
glacial bluff
#

just to confirm we are on the same page

ancient talon
#

yeah

#

also-

glacial bluff
#

in driver entity i added this

    @OneToOne(() => Vehicle, (vehicle) => vehicle.driver)
    vehicle: Vehicle;

after i imported vehicle
in vehicle entity

  @Column()
    vehicleDriverID: number;

    @OneToOne(() => Driver, (driver) => driver.vehicle) // note the back reference
    @JoinColumn({ name: 'vehicleDriverID' })
    driver: Driver;

removed the join column mad it like this
and finaly in the create vehicle dto the vehicle drive is number like this vehicleDriverID: number;

ancient talon
#

In school, Groklearning I've achevied a high disinction in world for python immerdiate so like ts is def not my thing-
(85-99% High Distinction)

glacial bluff
#

well not inferior but still FF SAKE

rancid pike
# glacial bluff now what?

Can you share the entire database and all your code? You keep asking partial questions when you're trying to get help with the bigger picture

glacial bluff
glacial bluff
rancid pike
# glacial bluff This is the full db
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import { Vehicle } from "../vehicle/vehicle.entity";
import { Member } from "../member/member.entity";

@Entity()
export class Driver {
    @PrimaryGeneratedColumn()
    driver_id: number;

    @Column()
    driver_name: string;

    @Column()
    driver_number: string;

    @Column()
    driver_region: string;

    @OneToMany(() => Vehicle, vehicle => vehicle.driver)
    vehicles: Vehicle[];

    @OneToMany(() => Member, member => member.driver)
    members: Member[];
}

here's an example of how driver would look

glacial bluff
rancid pike
glacial bluff
#

No |- is a one to one

rancid pike
glacial bluff
glacial bluff
rancid pike
#

I was looking at the wrong part mb

#
import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from "typeorm";
import { Vehicle } from "../vehicle/vehicle.entity";

@Entity()
export class Driver {
    @PrimaryGeneratedColumn()
    driver_id: number;

    @Column()
    driver_name: string;

    @Column()
    driver_number: string;

    @Column()
    driver_region: string;

    @OneToOne(() => Vehicle, vehicle => vehicle.driver)
    vehicle: Vehicle;
}

Try this