簡體   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