属于关联Golang Gorm没有找到明确的ForeignKey

时间:2016-06-28 21:35:10

标签: go go-gorm

我有一个像这样的Trade结构:

type Trade struct {
    ID            uint
    BuyExecution  Execution `gorm:"ForeignKey:BuyExecution"`
    SellExecution Execution `gorm:"ForeignKey:SellExecution"`
    Px            int
    Shares        int
}

这样的执行结构:

type Execution struct {
    ID                uint
    Side              string
    Symbol            string
    Trade             *Trade
}

架构:

CREATE TABLE `executions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `side` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `symbol` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `trade_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;



CREATE TABLE `trades` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `buy_execution_id` int(11) NOT NULL,
  `sell_execution_id` int(11) NOT NULL,
  `px` int(11) NOT NULL,
  `shares` int(11) NOT NULL,
  `trade_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

然而,当创建执行然后从具有适当关系的yaml灯具进行交易时,我收到了错误:

[2016-06-28 21:17:50]  sql: converting Exec argument #0's type: unsupported type models.Execution, a struct 

指向我在此处Preload来电:

var trade Trade
db.Preload("BuyExecution").First(&trade)

调试这个很困难所以试图获得一些帮助。

1 个答案:

答案 0 :(得分:1)

像这样定义你的Trade结构

type Trade struct {
    ID              uint
    BuyExecution    Execution `gorm:"ForeignKey:BuyExecutionID"`
    BuyExecutionID  int
    SellExecution   Execution `gorm:"ForeignKey:SellExecutionID"`
    SellExecutionID int
    Px              int
    Shares          int
}

甚至

type Trade struct {
    ID              uint
    BuyExecution    Execution
    BuyExecutionID  int
    SellExecution   Execution
    SellExecutionID int
    Px              int
    Shares          int
}