Php foreach在twig symfony2中使用sql
我有以下PHP代码:Php foreach在twig symfony2中使用sql,php,symfony,twig,Php,Symfony,Twig,我有以下PHP代码: $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('DataBundle:SomeData')->findAll(); foreach ($entity as $item) { echo $item->getSomething(); $data = $em->getRepository('DataBundle:SomeDa
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('DataBundle:SomeData')->findAll();
foreach ($entity as $item)
{
echo $item->getSomething();
$data = $em->getRepository('DataBundle:SomeData')
->findBySomeId($item->getSomeId());
foreach ($data as $somevar)
{
echo $somevar->getSomeOtherData();
}
}
它能用细枝翻译吗?如果是这样的话,我会很感激你给我指点如何做到这一点
谢谢您需要在模型中进行实体计算,由控制器启动,并将这些对象传递到视图中,以便推送到模板引擎中 树枝看起来像这样:
{% for item in entity %}
{{ item.getSomething }}
{% for somevar in data %}
{{ somevar.getSomeOtherData }}
{% endfor %}
{% endfor %}
编辑:这里有一个更精确的答案,你可以从这里推断:
// Controller
public function demoAction()
{
$demoModel = $this->get('demo.bundle.model.demo');
$demoView = $this->get('demo.bundle.view.demo');
$demoResult = $demoModel->myModelCalculation();
return $demoView->myDemoView($demoResult);
}
//Model
public function myModelCalculation()
{
return $this->getRepository('DataBundle:SomeData')->findAll();
}
//View
public function myDemoView($entity)
{
return $this->getTemplatingEngine()->renderResponse('DemoBundle:demo:index.html.twig', array('entity' => $entity));
}
//Twig
{% for item in entity %}
{{ item.getSomething }}
{% endfor %}
Symfony2很容易学习,我建议你学习他们的教程并阅读文档。
为您添加了一些额外的内容/方向。Symfony不是MVC框架。我认为为模型和视图创建服务在这里是不必要的。此外,“数据”细枝变量必须依赖于“项目”的id,所以最好在entity@Ziumin,让我们看看你的答案。Symfony的性能不会因为使用MVC结构而受到任何阻碍,它提供了更好的长期管理代码的能力。尽管如此,你不能从OP的问题中判断这是否必要,这也没有错,这是不可能的。你在树枝上找不到什么东西。如果要使用双循环,则必须构建哈希数组或在实体之间使用绑定。
//SomeData.php
// ....
class SomeData
{
// ...
/**
* @ORM\OneToMany(targetEntity="SomeData")
*/
private $children;
}
//Controler
class SomeController
{
/**
* @Template()
*/
public function someAction()
{
return ('entities' => $this->getDoctrine()->getRepository('DataBundle:SomeData')->findAll());
}
}
//some.html.twig
{% for item in entities %}
{{ item.getSomething }}
{% for somevar in item.children %}
{{ somevar.getSomeOtherData }}
{% endfor %}
{% endfor %}