原则一对多关系

Doctrine One to Many relationship

我对一对多关系的学说感到困惑。

问题一:

如果我错了请纠正我。我假设当我尝试

$em = $this->getDoctrine()->getManager();
$product_repo = $em->getRepository('MyBundle:Product');
$products = $product_repo->findAll();
dump($products);

我将看到附加到 $features 变量的相关功能,因此当我使用 $products->getFeatures() 时,我将拥有数组形式的 Feature 对象。但是从转储调试中我没有看到任何附加的东西而是我得到了这个:

另一端我也是这样做的

$em = $this->getDoctrine()->getManager();
$feature_repo = $em->getRepository('MyBundle:Features');
$features = $product_repo->findAll();
dump($features);

这次我可以看到 Product 对象附加到 $product 变量。

我的问题是,我无法从变量$features 获取数据有什么问题吗?否则doctrine默认不会加载相关数据

问题二:

如果我们假设数据能够加载到特征 $variable 中,我是否可以过滤数据(例如,where feature.name = 'fly')而不是加载所有相关功能。

=========================================== =============================

我的演示实体

<?php
use Doctrine\Common\Collections\ArrayCollection;

/** @Entity **/
class Product
{
    // ...
    /**
     * @OneToMany(targetEntity="Feature", mappedBy="product")
     **/
    private $features;
    // ...

    public function __construct() {
        $this->features = new ArrayCollection();
    }
}

/** @Entity **/
class Feature
{
    // ...
    /**
     * @ManyToOne(targetEntity="Product", inversedBy="features")
     * @JoinColumn(name="product_id", referencedColumnName="id")
     **/
    private $product;
    // ...
}

产品table(在数据库中): ID、描述、名称

特征table(在数据库中): ID,描述,名称,table_id

假设您的转储函数是 symfony/var-dumper 而不是自定义函数

问题 1

是的,转储功能默认不显示嵌套集合,这与性能有关。这不是与学说相关的问题。您的数据已加载到此处。

您可以尝试使用 var-dumper 的高级用法,例如脚轮 (http://symfony.com/doc/current/components/var_dumper/advanced)

问题 2

您有不同的方法来解决您的问题:

在控制器中:在产品中创建自定义方法

标准更好的解决方案

Product::getFeaturesByName($name='fly'){
  $criteria = Criteria::create();
  $criteria->where(Criteria::expr()->eq('name', $name));
  return $this->features->matching($criteria);
}

过滤器

Product::getFeaturesByName($name='fly'){

  return $this -> features ->filter(
      function($entry) use ($name) {
         return $entry->getName() == $name;
      }
  );
}

); }

在 Twig 模板中:循环过滤

{% for product in products %} {# start browse products #}
  {% for feature in product.features if feature.name='ok' %}{# start browse features #}

  {% endfor %}{# end browse features #}
{% endfor %}{# end browse products #}

希望对您有所帮助

问候