繁体   English   中英

Doctrine/Symfony - 同一 Model 上的多个一对多关系

[英]Doctrine/Symfony - Multiple one-to-many relations on same Model

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

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

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

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

我首先在我的软件 model 上尝试了如下所示的内容,但该关系仅适用于第一个本地引用 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 子句中仅考虑发布者。

所以最后,我的问题是,如何处理同一个 model 的多个一对多关系? 谢谢你的时间 !

也许您应该尝试添加一个外部别名来告诉 doctrine 在触发查询时要处理哪个关系:

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')
 ;

The doctrine default is to use the model name as identifier for the relation, so if using more then one relation to the same model you really should rename at least one to let doctrine now what you're meaning. 没有这个,您将无法像这样检索已发布软件的集合:

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

Doctrine 不能(恕我直言)将这两种关系与相同的 model 视为一个关系。 所以一个电话:

$allSoftware = $myCompany->getSoftware();

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

希望有帮助,

~~~ 干杯。

暂无
暂无

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

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