[英]Doctrine, how to join tables with many to many relation
我正在使用Symfony 2,Doctrine和Query Builder。 我有2個表格:產品和類別。
產品ORM文件包含以下內容:
manyToMany:
categories:
targetEntity: Pim\Component\Catalog\Model\CategoryInterface
joinTable:
name: pim_catalog_category_product
joinColumns:
product_id:
referencedColumnName: id
onDelete: CASCADE
inverseJoinColumns:
category_id:
referencedColumnName: id
onDelete: CASCADE
這樣做的效果是,我有一個名為“ pim_catalog_category_product”的表,該表鏈接了帶有產品的類別。 我的類別ORM文件中沒有有關產品的信息。
我正在嘗試使用QueryBuilder建立查詢,但我不明白如何從類別表查詢開始,該表鏈接產品以在產品上添加一些過濾器。
$qb = $this->getEntityManager()
->createQueryBuilder()
->addSelect('category')
->from($this->_entityName, 'category')
->join('Pim\Component\Catalog\Model\Product', 'product', 'WITH', 'category.id IN (product.categories);
但是現在我得到以下錯誤:
Expected Literal, got 'product' at ... SELECT category FROM Pim\\Bundle\\CatalogBundle\\Entity\\Category category INNER JOIN Pim\\Component\\Catalog\\Model\\Product product WITH category.id IN (product.categories) at ...
有人可以幫我嗎? 謝謝。
當您使用ManyToMany原則時,您會在關系管理的背景中為您做很多“魔術”操作,因此您可以進行快速聯接,而無需考慮聯接的笛卡爾積
$this->getEntityManager()
->createQueryBuilder()
->addSelect('product')
->from($this->_entityName, 'p')
->join('p.category')
或快速沖洗
$product->setCategories($categories);
$em->persist($product);
$em->flush();
缺點是,要使學說能夠執行此“魔術”,您無權訪問需要執行所需聯接的內部聯接表。
另外,如果您未在“類別”上定義相反的關系,則我認為教義不能為您管理這種連接。 但是請注意,如果您有很多產品,這樣做會占用大量內存,因為主義會延遲加載您類別中的所有產品。
如果您不想定義反向關系(由於上述問題),一種解決方法是在關系表上定義一個實體(類似於ProductCategory),並在2上定義2 1-> 1關系該實體的列。 然后,無論何時要創建從Category開始並與Product聯接的查詢生成器,都可以將此實體用作橋梁,而不必在Category上定義M <-> M關系
就像是
$qb = $this->getEntityManager()
->createQueryBuilder()
->addSelect('c')
->from($this->_entityName, 'c')
->join('Pim\Component\Catalog\Model\ProductCategory', 'pc', 'WITH', 'c.id = pc.category_id')
->join('Pim\Component\Catalog\Model\Product', 'p', 'WITH', 'p.id = pc.product_id')
PS:嘗試像上面的示例一樣使用短別名,以避免出現更多的“文字上的”異常。
希望這可以幫助,
亞歷山德魯·科索伊
我終於設法通過子查詢和從ManyToMany關系聯接表的正確方法解決了我的問題。
$qb2 = $this->getEntityManager()
->createQueryBuilder()
->addSelect('product_category.id')
->from('Pim\Component\Catalog\Model\Product', 'product')
->join('product.categories', 'product_category');
在我的主要查詢中:
$qb->andWhere($qb->expr()->in('category.id', $qb2->getDQL()));
謝謝Alexandru Cosoi和Stmm提供的有用信息!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.