Damon
Damon

Reputation: 4524

NestJs: How can I import one repository into another?

I apologize for what is likely a very amateur question. Coming from Laravel, this is still quite confusing to me and I just don't understand what is needed.

I have a user.repository.ts file and a location.repository.ts file. Each have their own modules, controllers and services. I have successfully created CRUD operations for each entity but now am trying to work towards a Many to Many relationship.

In my user.repository.ts file, I am trying to save a related (many to many) repository:

// user.repository.ts

user.locations = await this.locationRepository.findByIds(locations);
...

await user.save();

I am not sure how to inject or import the location.repository.ts file. I have tried numerous variations of importing the service into each module. Or importing each module into the other module. I have tried different versions of this:

@EntityRepository(User)
@EntityRepository(Location)

Or importing the LocationService into the UserService.

In Laravel, this would be as "simple" as $model->sync($relationship);

How can I import/inject the locationRepository into my userRepository? Thank you for any suggestions!

Upvotes: 1

Views: 3845

Answers (1)

Ayoub Touba
Ayoub Touba

Reputation: 2997

I assume this question is related to your last question, the simplest way to implement it, Add Locationentity to your UserModule

@Module({
imports:[TypeOrmModule.forFeature([UserRepository,LocationRepository])], // or just Location entity [UserRepository,Location] if you didn't setup a custom LocationRepository

After that, inject it in your as what you did for userRepo... service

constructor(
    @InjectRepository(LocationRepository)
    private locationRepository: LocationRepository,
    // or just  private locationRepository: Repository<Location>,
  ) {}

In the create method service get your locations:

 async  createUser(createUserDto: CreateUserDto) { // usersSrvice
let locations = await this.locationRepository.findByIds(createUserDto.locations);
await this.userRepository.createMethodeName(createUserDto,locations) // add secand 
params for your locations 

don't hesitate to ask if you have any other questions

Upvotes: 5

Related Questions