我使用的是Symfony 3.4.1,带有学说/ORM 2.5.13。我有2张桌子。store
和store_product
。
在Store
实体中我有:
/**
* @ORMOneToMany(targetEntity="AppBundleEntityStoreProduct", mappedBy="store")
* @ORMJoinColumn(name="store_id")
*/
private $products;
,在StoreProduct
实体中,我具有(store_id,product_id)的复合索引。我有:
/**
* @ORMManyToOne(targetEntity="AppBundleEntityStore", inversedBy="products")
* @ORMJoinColumn(name="store_id",referencedColumnName="id",nullable=false,onDelete="CASCADE")
* @ORMId()
* @ORMGeneratedValue("NONE")
* @var $store AppBundleEntityStore
*/
protected $store;
/**
* @ORMManyToOne(targetEntity="AppBundleEntityProduct", inversedBy="stores")
* @ORMJoinColumn(name="product_id",referencedColumnName="id",nullable=false,onDelete="CASCADE")
* @ORMId()
* @ORMGeneratedValue("NONE")
* @var $product AppBundleEntityProduct
*/
protected $product;
早些时候,我使用指南制作了本机查询。它只是从 store
表中获取条目,而且效果很好。
现在,我正在尝试加入store_product
表,但进展不佳。我正在使用以下查询,以返回1结果。
SELECT st.id, st.name, stp.store_id, stp.product_id, stp.price FROM store st LEFT JOIN store_product stp ON st.id = stp.store_id WHERE st.id=1 LIMIT 1;
返回类似:
id | name | store_id | product_id | price
----+------------+----------+------------+-------
1 | Store Name | 1 | 1234567890 | 129
我设置结果集映射如下:
$rsm = new ResultSetMapping();
$rsm->addEntityResult('AppBundleEntityStore', 'st');
$rsm->addFieldResult('st', 'id', 'id');
$rsm->addFieldResult('st', 'name', 'name');
$rsm->addJoinedEntityResult('AppBundleEntityStoreProduct', 'stp',
'st', 'products');
$rsm->addFieldResult('stp','store_id', 'store');
$rsm->addFieldResult('stp','product_id','product');
$rsm->addFieldResult('stp','price','price');
我遇到错误:Notice: Undefined index: store
可以看到错误的原因吗?
我设法在3个月后终于工作了。
显然,当我在addFieldResult()
中添加外国键以加入表时,我犯了一个错误的信任文档。
我需要删除store_id
和product_id`的addFieldResult()
行,然后将它们添加为:
$rsm->addMetaResult('stp', 'store_id', 'store_id', true);
$rsm->addMetaResult('stp', 'product_id', 'product_id', true);
仅使用addMetaResult()
添加它们不足
即使文档说Consequently, associations that are fetch-joined do not require the foreign keys to be present in the SQL result set, only associations that are lazy.
对我有用的是从ResultSetMappingBuilder
而不是addJoinedEntityResult
使用addJoinedEntityFromClassMetadata
。使用文档中的示例:
/**
* @param string $class The class name of the joined entity.
* @param string $alias The unique alias to use for the joined entity.
* @param string $parentAlias The alias of the entity result that is the parent of this joined result.
* @param string $relation The association field that connects the parent entity result
* with the joined entity result.
*/
$rsm->addJoinedEntityFromClassMetadata(Address::class, 'a', 'u', 'address');