doushou7169 2017-03-25 14:36
浏览 103
已采纳

数据存储-如何将Key放入结构ID(golang)中?

I'm trying to build a many to many relationship, so I have 3 structs:

type Orders struct {
  ID int64
  CustomerID string
  etc
}

type Products struct {
  ID int64
  Name string
  Description string
  etc
}

type OrderDetails struct {
  OrderID int64
  ProductID string
  Quantity int
}

I believe this is the right way to do it, but my problem now is that I do not know how to put the datastore key inside the struct ID without making two client.Put requests because as far as I can tell, datastore.IncompleteKey("Products", nil) will not return the new key value until after you put it..

I guess some people would recommend using key *datastore.Key instead of ID int64, but I would prefer to convert the key to an ID

Any help would be much appreciated

  • 写回答

1条回答 默认 最新

  • dra87370 2017-03-25 16:56
    关注

    One option is to allocate keys in advance, which you can set in your structs prior to calling Client.Put().

    You can allocate IDs with the Client.AllocateIDs(). You can pass a slice of incomplete keys to it, and you get back a slice of complete datastore.Keys, which the datastore reserves for you (and thus guarantees not to "give out" to others or use when saving entities with incomplete keys). You can access the numeric IDs of the allocated keys in the Key.ID field.

    But storing the numeric Key ID in the entities is redundant, and I find it a waste (of resources). Whenever you load an entity e.g. with Client.Get(), or multiple with Client.GetAll(), you also get back the keys, and you can fill the numeric IDs in the structs "manually" as a post-processing step. You can also wrap this post-processing functionality in a function which does this for you whenever you get entities from the datastore.

    For example, if you have an OrderDetails entity loaded, which contains the OrderID, you may use datastore.IDKey() to construct the datastore.Key for the respective Order entity. Example doing it:

    var orderDetails OrderDetails
    // Load orderDetails
    
    orderKey := datastore.IDKey("order", orderDetails.OrderID, nil)
    // Now you have the key for the Order entity
    
    var order Order
    err := client.Get(ctx, orderKey, &order)
    

    Which means you shouldn't store the "self ID" in the entities, you can construct datastore.Key values if the numeric ID is known.

    Also see related question: Can I use AllocateIDs as "string" ? datastore

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c