Gorm: Preloading soft deleted relationships?

Created on 4 Mar 2016  路  5Comments  路  Source: go-gorm/gorm

Is there a way to preload soft deleted related data?

Let's say I have an Event model and Team model.

A soft deleted team belongs to an event.

How can I preload the soft deleted team when fetching the event?

missing reproduction steps

Most helpful comment

package main

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type Team struct {
    gorm.Model
    Name   string
    Events []Event
}

type Event struct {
    gorm.Model
    TeamID uint
    Name   string
}

func main() {
    db, err := gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
    if err != nil {
        panic(err)
    }
    db.SingularTable(true)
    db.LogMode(true)
    db.AutoMigrate(&Team{})
    db.AutoMigrate(&Event{})

    db.Create(&Team{})
    db.Unscoped().Debug().Preload("Events", func(db *gorm.DB) *gorm.DB {
        return db.Unscoped()
    }).Find(&Team{})
}

http://jinzhu.me/gorm/curd.html#custom-preloading-sql

All 5 comments

Unscoped

@jinzhu It doesn't work for preloading soft deleted relationships.

In my example above, if the event is soft deleted, I can fetch the soft deleted events using Unscoped:

db.Unscoped().Find(&events)

But what I want to achieve is to preload the soft deleted relationships (teams) of each events.

Hello @basco-johnkevin

Could you submit a runnable script for testing? https://github.com/jinzhu/gorm/blob/master/CONTRIBUTING.md

I'll try to submit a runnable script later. By the way, my issue and use case is related to this - http://stackoverflow.com/questions/20102696/laravel-4-eloquent-soft-deletes-and-relationships

package main

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type Team struct {
    gorm.Model
    Name   string
    Events []Event
}

type Event struct {
    gorm.Model
    TeamID uint
    Name   string
}

func main() {
    db, err := gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
    if err != nil {
        panic(err)
    }
    db.SingularTable(true)
    db.LogMode(true)
    db.AutoMigrate(&Team{})
    db.AutoMigrate(&Event{})

    db.Create(&Team{})
    db.Unscoped().Debug().Preload("Events", func(db *gorm.DB) *gorm.DB {
        return db.Unscoped()
    }).Find(&Team{})
}

http://jinzhu.me/gorm/curd.html#custom-preloading-sql

Was this page helpful?
0 / 5 - 0 ratings

Related issues

koalacxr picture koalacxr  路  3Comments

izouxv picture izouxv  路  3Comments

youtwo123 picture youtwo123  路  3Comments

satb picture satb  路  3Comments

bramp picture bramp  路  3Comments