简体   繁体   English

如何获取额外数据以提供symfony2集合字段类型?

[英]How to fetch extra data to feed a symfony2 collection field type?

I am using a basic collection field with Symfony2, and everything is working well. 我正在使用Symfony2的基本收集字段,一切都运行良好。

Say I have: 说我有:

->add('product', 'collection', array(...))

Now, in my view, I am calling product.vars.data.owner where I have a oneToOne product->getOwner() . 现在,在我看来,我正在调用product.vars.data.owner ,我有一个oneToOne product->getOwner()

This is generating one extra request per product in the collection. 这会在集合中为每个产品生成一个额外请求。 Since I can't use a querybuilder in a collection field, how can I make sure it doctrine fetches the product owners in order to avoid those many extra requests? 由于我不能在集合字段中使用querybuilder,我如何确保它的学说取得产品所有者以避免那些额外的请求?

This is an example(I don't see your data mapping & form builder), I hope this help you : 这是一个示例(我没有看到您的数据映射和表单构建器),我希望这可以帮助您:

1 : Fetch your data by dql , 1:通过dql获取数据,

$dql = "select c from category c left join c.product p join p.owner o where c.id = ?1";
$category = $this->createQuery($dql)->setParameter(1, $id)->getSingleResult();

2 : Suppose you have a category form that could have many products: 2:假设您有一个可能包含许多产品的类别表单:

class Category
{
    // manyToMany
    private $product
}

$form = $this->createForm(new CategoryType(), $category);

3 : If your collection type be an embedded ProductType(form type) then you can use below line in your template: 3:如果您的集合类型是嵌入式ProductType(表单类型),那么您可以在模板中使用以下行:

{{ form.product.vars.data.owner }} 

If you can't use a querybuilder you could force Doctrine to always load the owner on the product whenever the product is loaded by EAGER loading the association: 如果你不能使用querybuilder,你可以强制Doctrine在EAGER加载产品加载产品时,始终在产品上加载所有者:

/**
 * @ORM\OneToOne(targetEntity="Application\Entity\Owner", fetch="EAGER")
 */
protected $owner;

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#by-eager-loading http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#by-eager-loading

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

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