2012-11-15 90 views
-1

我在PHP下面的SQL代碼:的foreach在樹枝的Symfony2

$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(); 
    } 
} 

是否可以在枝條翻譯?如果是這樣,我將不勝感激指示如何可以完成。

感謝

+0

這是不可能的。你無法找到樹枝上的東西。 如果你想使用雙週期,你必須建立散列數組或使用實體間的綁定。 – Alastor

回答

1

你需要做你的實體的計算模型中,由控制器發起,並通過這些對象到您的視圖被推入到您的模板引擎。

樹枝應該是這樣的:

{% 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的簡單易學,我建議做他們的教程和閱讀文檔。 http://symfony.com/doc/current/index.html

+0

爲您增加了一些額外的內容/方向。 – phpisuber01

+0

Symfony不是MVC框架。我認爲爲模型創建服務,在這裏不需要視圖。 「數據」的小枝變量必須依賴於「item」的id,所以最好在實體 – Ziumin

+0

@Ziumin中使用OneToMany doctrine關聯,讓我們看看你的答案。無論如何,Symfony的性能不會受到阻礙,並且可以提供更好的長期管理代碼的能力。儘管如此,你不能從OP的問題中確定這是否有必要,也沒有錯。 – phpisuber01

0
//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 %}