Php 一对多关系学说
我对一对多的关系感到困惑 问题1: 如果我错了,请纠正我。我想当我试图Php 一对多关系学说,php,symfony,doctrine-orm,doctrine,one-to-many,Php,Symfony,Doctrine Orm,Doctrine,One To Many,我对一对多的关系感到困惑 问题1: 如果我错了,请纠正我。我想当我试图 $em = $this->getDoctrine()->getManager(); $product_repo = $em->getRepository('MyBundle:Product'); $products = $product_repo->findAll(); dump($products); 我将看到附加到$features变量的相关特性,因此,当我使用$products->getFea
$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获取数据,有什么问题吗?或者默认情况下,条令不会加载相关数据。
问题2:
如果我们假设数据能够加载到feature$变量中,我是否可以过滤数据(例如,其中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;
// ...
}
假设您的转储函数是symfony/var转储程序,而不是自定义函数
问题1
是的,默认情况下,转储函数不会显示嵌套集合,这与性能有关。这不是一个与理论相关的问题。您的数据在这里加载
您可以使用高级的var转储程序,比如casters()
问题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;
}
);
}
));
}
在细枝模板中:在循环中过滤
希望这对你有帮助
问候非常感谢您,祝您今天愉快。关于问题2,我还有另外一个问题,这里列出的所有方法都将加载我输入的特定值,还是仍将加载数据库中的所有值并对程序进行过滤?按条件是最优化的解决方案:如果集合不是从数据库加载的,它将只选择与条件匹配的实体。通过过滤器或细枝解决方案加载数据库中的所有数据,并在“程序”上进行过滤。
{% 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 #}