【问题标题】:How to set an entity field that does not exist on the table but does exists in the raw SQL as an alias?如何将表上不存在但在原始SQL中存在的实体字段设置为别名?
【发布时间】:2012-04-01 11:43:40
【问题描述】:

假设我们有这样一个查询:

SELECT *, (CUSTOM_EXPRESSION) as virtualfield FROM users

用户的实体本身有“虚拟字段”但映射注释没有,因为表没有这个字段。

假设它是作为原始 SQL 执行的,我们如何使用上面的字段填充实体?

【问题讨论】:

    标签: php sql doctrine-orm rawsql


    【解决方案1】:

    我找到了答案。为此,您需要使用标量值。例如:

    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
    $rsm->addRootEntityFromClassMetadata('Category', 'c');
    $rsm->addScalarResult('depth', 'depth');
    // [ ... ]
    $results = $q->execute();
    // Output will be a two-dimensional array 
    // array(0 => array(0 => CategoryObject, 'depth' => 'scalar-value', // ... ), // ...)
    

    然后,您可以遍历它并根据需要设置对象的属性。

    【讨论】:

      【解决方案2】:

      我不完全确定我明白你在问什么。我假设您想知道如何使用 (CUSTOM_EXPRESSION) 更新 users.virtualfield?该语法将是:

      update users set virtualfield = (CUSTOM_EXPRESSION)
      

      如果您想更新所有行。

      如果我说错了,你能澄清一下你的问题吗?

      【讨论】:

      • 当然可以。实际上我指的是 Doctrine ORM,SQL 只是一个仅存在于查询上下文中的字段的示例。在 Doctrine 上,AFAIK 您只能填充映射到表上字段的对象,但不能填充在 SELECT 语句中作为别名创建的字段。我想你还没有看到教义标签。正确的?您的回答是关于 SQL 更新 =) 我的问题是关于 Doctrine。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      相关资源
      最近更新 更多