【问题标题】:Dynamic property defaults in CF9 ORMCF9 ORM 中的动态属性默认值
【发布时间】:2010-08-16 14:12:07
【问题描述】:

如何在 CF9 ORM 对象上设置动态属性默认值?

例如,我知道我可以像这样设置属性默认值:

property name="isActive" default="1";

但是,如果您想要动态生成默认值,例如日期或 UUID,该怎么办?

property name="uuid" default="#createUUID()#";

...引发错误 - 那么解决方法是什么?

【问题讨论】:

    标签: orm coldfusion


    【解决方案1】:

    创建实体对象时,会调用对象构造函数。这是运行“设置”代码的好地方。

    用户.cfc

    component persistent="true"
    {
      property name="id" fieldtype="id" generator="native";
      property name="secretKey";
    
      public User function init() {
         if (isNull(variables.secretKey))
             setSecretKey(createdUUID());
    
         return this;
      }
    }
    

    【讨论】:

    • 这适用于新实体,但会被从数据库加载的任何内容覆盖(即使它是空白值)。然而,由于我是从头开始构建这个应用程序,没有遗留数据,我可以确定用户数据库中的每个条目都将使用这个默认值创建。 (在上面的代码中,init() 函数需要“return this;”添加到末尾。)谢谢,Seb
    • 如果您只想为新实体运行此代码,您可以随时检查实体的 id if(isNull(getId()){ }
    • 另一种方法是分配 uuid @preInsert
    • Henry 建议使用 orm 事件处理程序 cfc 的链接http://www.danvega.org/blog/index.cfm/2009/12/22/ColdFusion-9-ORM-Event-Handlers-Use -案例
    【解决方案2】:

    您是否尝试过重载 getter?

    public string function getUUID() {if(variables.UUID EQ ""){ return createUUID(); } else { return variables.firstName; }; }
    

    我无法从我所在的位置进行测试,但我会尝试。

    【讨论】:

    • Dan,我认为他需要将其设为默认值,而不总是返回新的 UUID。如果 UUID 已经存在于数据库中怎么办?
    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多