skip to Main Content

I have question regarding fetching foreign key in GORM.
I am using golang and POSTGRES for my database.
AFAIK, Preload(clause.Associations) will fetch the foreign key from our database.

If we are using Gorm .Find(&model), its automatically fetching my foreign key detail
But if I am using Raw Query .Raw(), its not fetching the foreign key

here is the example
my model

type BankAccount struct {
    gorm.Model `json:"-"`

    ID    uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4();primary_key" json:"id"`
    OrgId uuid.UUID `gorm:"type:uuid;not null" json:"orgId"`

    AccountName   string    `gorm:"not null" json:"accountName"`
    AccountNumber string    `gorm:"not null" json:"accountNumber"`
    AccountType   string    `gorm:"not null" json:"accountType"`
    BankId        uuid.UUID `gorm:"not null" json:"bankId"`
    Bank          *Bank     `gorm:"foreignKey:BankAccountId" json:"bank"`
}

if I use db.Preload(clause.Associations).Find(&BankAccount), it automatically fetching bank field.

{
    "id": "999e5e1f-dfd2-498f-a856-6a021052",
    "orgId": "bbd38cbe-3eef-4587-a178-eb3148",
    "accountName": "Account 1 Neo Bank",
    "accountNumber": "8237372323",
    "accountType": "debit",
    "bankId": "89c-5ff8-4b13-b8c3-dd3b3be690b5",
    "bank": {
        "id": "89c-5ff8-4b13-b8c3-dd3b3be690b5",
        "orgId": "bbd38cbe-3eef-4587-a178-eb316b729148",
        "name": "Neo Bank",
        "address": "Addr 2",
        "contactInfo": "081333333",
        "remarks": "neo bank"
    }
}

but if I am using raw query like this db.Preload(clause.Associations).Raw("select * from bank_account").scan(&bankAccounts), it wont fetch the bank field

[
{
    "id": "999e5e1f-dfd2-498f-a856-6a021052",
    "orgId": "bbd38cbe-3eef-4587-a178-eb3148",
    "accountName": "Account 1 Neo Bank",
    "accountNumber": "8237372323",
    "accountType": "debit",
    "bankId": "89c-5ff8-4b13-b8c3-dd3b3be690b5",
    "bank": null
}
]

Am I doing it wrong?

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    I will answer my own question.

    Actually I am not doing it wrong. It just .Preload() cant run if we use Raw().

    and here is what I discover:

    Recently, I saw the log from GORM using .Debug() func. .Preload() actually running another query and put the result on the struct result.

    Now, I changing my method to use .Raw() function and make another struct to put the result. and it works fine. whenever I have a complex query, I will use this method.

    Hope it helps Thanks


  2. You are using raw query that means gorm will execute this plain query without modifying any thing into it. So gorm will not join bank_account table with bank table. You have to explicitly do that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search