简体   繁体   English

根据外键关系获取GORM模型行(golang)

[英]Get GORM model row based on foreign key relationship (golang)

I am using Golang (GORM) + Postgres.我正在使用 Golang (GORM) + Postgres。 I am trying to model a business situation where a seller sells things to buyers, each creating an order transaction.我正在尝试模拟一种业务情况,即卖方向买方出售商品,每个人都创建一个订单交易。

I have an Order Gorm model, as well as a Buyer and a Seller Gorm model.我有一个 Order Gorm 模型,以及一个买方和一个卖方 Gorm 模型。 The Buyer and the Seller are already rows created in the database.买方和卖方已经是在数据库中创建的行。

One buyer HasMany orders.一位买家有许多订单。

One seller HasMany orders.一位卖家有许多订单。

To map out this relation, I believe I just create the respective Buyer/Seller struct (standard Gorm models), and then make an Order struct like so:为了绘制出这种关系,我相信我只是创建了相应的买方/卖方结构(标准 Gorm 模型),然后像这样创建一个 Order 结构:

type Order struct {
    ID        int64       `json:"ID"gorm:"primary_key;auto_increment:true"`
    Buyer     *Buyer      `json:"Buyer"`
    Seller    *Seller     `json:"Seller"`
    // ... other data ...
}

I'm assuming the above automatically creates the relationship, but I am not entirely sure .我假设上述自动创建关系,但我不完全确定 I can create an Order with this function, and this returns fine:我可以用这个函数创建一个订单,这返回正常:

func CreateOrder(buyer *entity.Buyer, seller *entity.Seller) (*entity.Order, error) {
    order := &entity.Order{
        User:   buyer,
        Sitter: seller,
        // ... other data ...
    }
    db.Table("orders").Create(order)
    return order
}

If I go to Postgres CLI, the TABLE orders;如果我转到 Postgres CLI,则TABLE orders; does not show the columns buyer or seller.不显示列买家或卖家。 I would expect a column of their IDs.我希望有一列他们的 ID。 So this is why I am unsure this is working.所以这就是为什么我不确定这是否有效。 This could definitely be a problem in itself.这本身肯定是一个问题。

Anyways, what I really want to do is be able to check if any orders currently exist for a Buyer / Seller.无论如何,我真正想做的是能够检查买方/卖方当前是否存在任何订单。 But I don't really see anyway to do that with gorm queries.但是我真的不认为用 gorm 查询来做到这一点。 I would imagine in SQL it would be something like:我想在 SQL 中它会是这样的:

func FindOrder(buyer *entity.Buyer, seller *entity.Seller) {
     db.Raw(`GET order FROM orders WHERE buyer = ?, seller = ?`, buyer, seller)
     // OR this ???
     db.Table("orders").First(buyer, buyer).First(seller, seller)
}

But I don't know of any Gorm helper function that actually does this.但我不知道实际执行此操作的任何 Gorm 辅助函数。 I also want this to be efficient because buyer and seller each have their ID primary keys.我也希望这样做是有效的,因为买家和卖家都有他们的 ID 主键。

How can I find an Order based on the Buyer / Seller like in the example above?如何根据买方/卖方找到订单,如上例所示?

As an alternative, I am thinking of adding (buyer ID + seller ID) to make a custom order ID primary_key .作为替代方案,我正在考虑添加(买方 ID + 卖方 ID)来制作自定义订单 ID primary_key This seems hacky though, as I feel like the whole point of relations is so I don't have to do something like this.不过,这似乎很棘手,因为我觉得关系的全部意义在于我不必做这样的事情。

If you need to see the seller id and the buyer id in the orders table, include two fields for that in your orders struct, also you can use the foreignKey tag to populate those fields (by default they are populated with the primary id of the associated table record, you can use references tag as mentioned here to change that).如果您需要在订单表中查看卖家 ID 和买家 ID,请在您的订单结构中包含两个字段,您也可以使用外foreignKey标签来填充这些字段(默认情况下,它们填充了订单的主 ID)关联的表记录,您可以使用这里提到的references标记来更改它)。

type Order struct {
    ID int64 `json:"id" gorm:"primary_key;auto_increment:true"`
    BuyerID int64 `json:"buyer_id" gorm:"index"`
    SellerID int64 `json:"seller_id" gorm:"index"`
    Buyer *Buyer `json:"buyer" gorm:"foreignKey:BuyerID"`
    Seller *Seller  `json:"seller" gorm:"foreignKey:SellerID"`
}

type Buyer struct {
    ID int64    `json:"id" gorm:"primary_key;auto_increment:true"`
    Name string `json:"name"`
}

type Seller struct {
    ID int64    `json:"id" gorm:"primary_key;auto_increment:true"`
    Name string  `json:"name"`
}

As for the function to find orders given the buyer AND the seller you can use something like,至于查找给定买家和卖家的订单的功能,您可以使用类似的东西,

func findOrders(db *gorm.DB, buyerID int,sellerID int)[]Order{
    orders := make([]Order,0)
    db.Where("buyer_id=? AND seller_id=?",buyerID,sellerID).Find(&Order{}).Scan(&orders)
    return orders
}

in contrast if you need to find orders for a given buyer OR the seller,相反,如果您需要查找给定买家或卖家的订单,

func findOrder(db *gorm.DB, buyerID int,sellerID int)[]Order{
    orders := make([]Order,0)
    db.Where("buyer_id=? OR seller_id=?",buyerID,sellerID).Find(&Order{}).Distinct().Scan(&orders)
    return orders
}

The index tag covers the indexing requirement for orders table. index标签涵盖了orders表的索引要求。

在此处输入图片说明

对大型查询使用简单的原始查询构建器https://perfilovstanislav.github.io/go-raw-postgresql-builder/#simple-example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM