我有兩個與多對多關系相關的物體:
/** @Entity */
class Foo {
/** @Column(type="integer") */
public int $id;
/** @ManyToOne(targetEntity="Foo") */ ?
?public int $parentId;
?/** @ManyToMany(targetEntity="Bar", inversedBy="foos") */
?public Collection $bars;
?public function __construct() {
?$this->bars = new ArrayCollection();
?}
}
/** @Entity */
class Bar {
?/** @Column(type="integer") */
?public int $id;
?/** @ManyToMany(targetEntity="Foo", mappedBy="bars") */
?public Collection $foos;
?public function __construct() {
?$this->foos = new ArrayCollection();
?}
}
這最終產生表bars,foos和foos_bars。
通常,這種關系很容易,FK 為foos_bars.foo_id和foo_bars.bar_id。
但對于特殊查詢,我需要把所有的Foo那些比賽小號或者其中一個Bar連接到任何foo.id 或 foo.parent_id
在 SQL 上,它會是這樣的:
SELECT DISTINCT foos.*
FROM foos
INNER JOIN foos_bars
ON (foos_bars.foo_id = foo.id or foos_bars.foo_id = foo.parent_id)
...這將獲得Foo我想要的所有s。
但是更愿意能夠使用查詢構建器,因為這個查詢有一些可選部分,并且通過QueryBuiler構建最終查詢比使用 SQL 字串更簡單。
是否可以使用 ORM 查詢生成器完成這種查詢?
我開始像這樣的事情:
$qb = $this->createQueryBuilder('f');
$qb->select('f')->distinct();
$qb->innerJoin('f.bars', 'b');
但這在邏輯上只是簡單地加入了宣告的 FK ......
uj5u.com熱心網友回復:
由于您無法修改映射以將中間表“公開”為獨立物體,因此我認為您無法使用 ORM 查詢生成器執行此操作。
但是,您始終可以使用 DBAL 查詢構建器來實作。您將保持使用查詢構建器的便利性,您將能夠執行您需要的自定義連接。唯一的缺點是您需要自己進行物件的水合作用,但這應該是平衡其他事情的小代價。
$qb = $this->getEntityManager()
->getConnection()
->createQueryBuilder();
$qb->from('foos', 'f');
$qb->select('f.*')
->distinct();
->innerJoin('f', 'foos_bars', 'fb', 'fb.foo_id = f.id or fb.foo.id = f.parent_id');
$queryResult = $qb->executeQuery();
$repositoryResult = [];
foreach ($queryResult->fetchAllAssociative() as $row) {
$foo = new Foo();
// HERE YOU WOULD HYDRATE $foo WITH THE CONTENTS OF $row
$repositoryResult[] = $foo;
}
return $repositoryResult;
ORM 在很多時候都非常方便和方便,但是在離開其限制并在更接近持久層的地方做事有用的時候,學習它通常是好的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394458.html
上一篇:Rails7每個檔案更改都會引發錯誤的引數數量錯誤(給定2,預期為5)
下一篇:從一張表創建兩個聚合虛擬表并加入
