【问题标题】:Propel ORM: Add a column from another table which is not connected with a direct foreign keyPropel ORM:从另一个表中添加一个没有直接外键连接的列
【发布时间】:2015-11-13 15:34:48
【问题描述】:

我想将另一个表中的 SQL 列添加到我的 Propel 查询中,但我无法使用普通的“->withColumn”语句来获得它。第二个表没有通过外键与第一个表连接,但对于第一个表中的每个条目,第二个表中都有一个条目。两个表之间的连接是来自另外两个表的两个 id。
为了更好地理解,这里是我的表格:

条目:

  • 身份证
  • 姓名
  • expert_id
  • contingent_id

收藏:

  • 身份证
  • 位置
  • expert_id
  • contingent_id

专家和特遣队:

  • 身份证
  • ...

我希望条目表中的所有条目都带有一个额外的列位置。每个条目都有一个收藏夹。使用 SQL 查询是没有问题的:

SELECT *, (SELECT position FROM favorit AS f WHERE e.expert_id = f.expert_id AND e.contingent_id = f.contingent_id) AS position FROM entry AS e

但我不知道如何使用 Propel 创建查询。 我试过了:

EntryQuery::create() ->filterByExpertId(1) ->withColumn("select position from favorit AS f where e.expert_id = f.expert_id and e.contingent_id = f.contingent_id", '_favorit_id', 'type: int') ->find();

但是 Propel 给了我一个错误

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select position from favorit AS f where e.expert_id = f.expert_id and e.continge' at line 1' in D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\Adapter\Pdo\PdoStatement.php:57 Stack trace: #0 D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\Adapter\Pdo\PdoStatement.php(57): PDOStatement->execute(NULL) #1 D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\Connection\StatementWrapper.php(194): Propel\Runtime\Adapter\Pdo\PdoStatement->execute(NULL) #2 D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\ActiveQuery\Criteria.php(2633): Propel\Runtime\Connection\StatementWrapper->execute() #3 D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\ActiveQuery in D:\Entwicklung\htdocs\zeiterfassung\vendor\propel\propel\src\Propel\Runtime\ActiveQuery\Criteria.php on line 2639

当条目表中存在另一个表的外键(如 contingent_id 或计算列)时,我可以从另一个表中添加一列:
EntryQuery::create() ->filterByExpertId(1) ->join('Entry.Contingent') ->withColumn('Contingent.name','_contingentName') ->withColumn("LEFT(TIMEDIFF(TIMEDIFF(timeEnd,timeBegin),pause),5)", '_duration', 'type: time') ->find();

【问题讨论】:

    标签: php sql orm propel


    【解决方案1】:

    我找到了解决问题的方法:

    $result = EntryQuery::create() ->filterByExpertId($id) ->join('Entry.Contingent') ->join('Contingent.Favorit') ->where('Favorit.expert_id = ?', $id) ->withColumn('Favorit.position','_position') ->find();

    有了这个,我得到了正确的答案。但我还有一个问题:

    如果条目中存在相应的专家和条件但没有收藏夹,则此条目将与我的实际查询不显示。在这些情况下,我也想要这个条目作为额外条目,但位置具有一些默认值,如 null 或 0(零)。

    【讨论】:

      猜你喜欢
      • 2016-01-07
      • 1970-01-01
      • 2013-08-06
      • 2021-09-22
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多