简体   繁体   English

如何使用anorm处理未分配的ID?

[英]How to handle unassigned IDs with anorm?

Anorm has the special type anorm.Pk for typed primary keys (and its subclass anorm.NotAssigned ). Anorm对于键入的主键(及其子类anorm.NotAssigned )具有特殊的类型anorm.Pk This allows to assign a NotAssigned value if the database is responsible for generating the relevant key. 如果数据库负责生成相关密钥,则可以分配NotAssigned值。

Is there an equivalent concept for foreign keys? 外键有等同的概念吗? I'm using type Long at the moment. 我目前正在使用Long类型。 However, if the foreign key is not yet known, I will have to assign a null value or replace the type by an Option[Long] . 但是,如果尚不知道外键,则必须分配一个null值或用Option[Long]替换类型。 This feels like it's not the way it's meant to be done, though. 但是,这似乎并不是它应该完成的方式。

Anorm doesn't offer functionality around relations. Anorm不提供围绕关系的功能。

Take your FK out of your model, but accept FKs as arguments to your CRUD, eg for creating a "Contrived" that belongs to a user: 将FK移出模型,但接受FK作为CRUD的参数,例如,创建属于用户的“人为”:

def create(c: Contrived, userId: Long)
  DB.withConnection { implicit connection =>
  val id = SQL("""
      insert into c
      (first, second, login_id)
      values
      ({first}, {second}, {login_id})
      """).on(
    'first -> c.first,
    'second -> c.second,
    'login_id -> userId

...etc ...等等

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

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