Mike Schmidt
Mike Schmidt

Reputation: 385

Proper way to query for a Has One Relationship

If I am looking for the Person with Credit Card Number CreditCardNumber Is this the proper way to do it?

type Person struct {
    gorm.Model
    Name            string
    CreditCard CreditCard 
}

type CreditCard struct {
    gorm.Model
    PersonID       *uint
    Number string
}

database.dbClient.
   Preload("CreditCard").
   Where("credit_card.number = ?", CreditCardNumber).
   Joins("left join credit_cards on person.id = credit_card.person_id AND credit_card.deleted_at is NULL").
   First(&Person)

Upvotes: 0

Views: 52

Answers (1)

Mohit Singh
Mohit Singh

Reputation: 505

db.Preload("Person").Find(&CreditCard)

Also I don't think PersonID should be a pointer.

Upvotes: 1

Related Questions