【问题标题】:Doctrine/Symfony - Multiple one-to-many relations on same ModelDoctrine/Symfony - 同一模型上的多个一对多关系
【发布时间】:2011-07-01 23:56:51
【问题描述】:

这是我实际拥有的架构的摘录

Software:
  columns:
    title:
      type: string(255)
    id_publisher:
      type: integer
    id_developper:
      type: integer

Company:
  columns:
    name:
      type: string(255)
    nationality:
      type: string(255)

如您所见,我的软件模型有两个外部引用:发布者和开发者。我希望为这两个引用中的每一个创建一个一对多的关系。问题是他们都是公司。

我首先在我的软件模型上尝试了如下所示的操作,但该关系仅适用于第一个本地引用 id_publisher。

relations:
  Company:
    type: one
    foreignType: many
    local: [id_publisher, id_developper]
    foreign: id

然后我尝试了(总是在软件模型上):

relations:
  Publisher:
    class: Company
    type: one
    foreignType: many
    local: id_publisher
    foreign: id
  Developper:
    class: Company
    type: one
    foreignType: many
    local: id_developper
    foreign: id

但是当我执行一个计算软链接到公司数量的查询时......

public function findAllQuery(Doctrine_Query $q = null) {
    $q = Doctrine_Query::create()
                    ->select('c.*, COUNT(s.id) AS count_software')
                    ->from('Company c')
                    ->leftJoin('c.Software s')
                    ->groupBy('c.id');

    return $q;
}

...在 COUNT 子句中只考虑发布者。

最后,我的问题是,如何处理同一模型的多个一对多关系? 感谢您的宝贵时间!

【问题讨论】:

    标签: php doctrine one-to-many


    【解决方案1】:

    也许你应该尝试添加一个外国别名来告诉教义在触发你的查询时要处理哪个关系:

    relations:
      Publisher:
        class: Company
        type: one
        foreignType: many
        foreignAlias: PublishedSoftware
        local: id_publisher
        foreign: id
      Developer:
        class: Company
        type: one
        foreignType: many
        foreignAlias: DevelopedSoftware
        local: id_developer
        foreign: id
    

    在您的查询中,您必须加入两个关系并对各个计数求和:

    $q = Doctrine_Query::create()
         ->select('c.*, COUNT(ps.id)+COUNT(ds.id) AS count_software')
         ->from('Company c')
         ->leftJoin('c.PublishedSoftware ps')
         ->leftJoin('c.DevelopedSoftware ds')
         ->groupBy('c.id')
     ;
    

    原则默认是使用模型名称作为关系的标识符,因此如果对同一模型使用多个关系,您确实应该重命名至少一个关系,以让原则现在成为您的意思。没有这个,您将无法像这样检索已发布软件的集合:

    $pubSoftware = $myCompany->getPublishedSoftware();
    $devSoftware = $myCompany->getDevelopedSoftware();
    

    Doctrine 无法做到的(恕我直言)是将两种关系视为同一模型。所以一个电话:

    $allSoftware = $myCompany->getSoftware();
    

    不会检索多关系模型上的所有相关软件,而只会检索那些可以通过名为Software 的关系检索到的软件。

    希望对你有帮助,

    ~~~干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2016-07-12
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      相关资源
      最近更新 更多