2015-07-21 51 views
0

我在我的數據庫中有查看錶,如何從這個視圖中檢索數據?Symfony 2中的Mysql Views Table

我試圖用

$em = $this->getDoctrine()->getEntityManager(); 
$query = $em->createQuery('SELECT * FROM my_views'); 
$result = $query->getResult(); 

,但它不工作。

+0

你裏面寫什麼你' createQuery'是原生SQL,而'createQuery'需要[DQL](http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html)語句。 –

+0

[使用Doctrine 2執行原始SQL]的可能重複(http://stackoverflow.com/questions/3325012/execute-raw-sql-using-doctrine-2) –

+1

您可以使用原生sql並將其映射到實體。請參閱[doc](http://docs.doctrine-project.org/en/latest/reference/native-sql.html#the-nativequery-class) – Matteo

回答

3

如果要執行一個簡單的SQL查詢,你可以這樣做:

$con = $this->getDoctrine()->getEntityManager()->getConnection(); 
$stmt = $con->executeQuery('SELECT * FROM my_views'); 
foreach ($stmt->fetchAll() as $row){ 
    print_r($row); 
} 

當您使用$em->createQuery(),你需要主義實體合作。

如果你想使用映射你的觀點,中庸之道創建一個實體:

namespace Your\Bundle\Entity; 

/** 
* @ORM\Entity 
* @ORM\Table(name="my_view") 
*/ 
class MyView 
{ 
    /** 
    * @ORM\Column(type="integer") 
    * @ORM\Id 
    */ 
    protected $id; 

    /** 
    * @ORM\Column(type="string") 
    */ 
    protected $someVarcharColumn; 

    public function getId() 
    { 
     return $this->id; 
    } 

    public function getSomeVarcharColumn() 
    { 
     return $this->someVarcharColumn; 
    } 
} 

你還可以用DQL查詢這樣的:

$results = $em->createQuery(' 
    SELECT v 
    FROM YourBundle:MyView v 
')->getResult(); 
+0

這麼好,我可以做一個映射觀點?我想要吸氣劑方法 – monkeyUser

+0

是的,我更新了我的答案 –

+0

感謝您的時間。我必須以「手動」的方式創建一個實體,我不能讓這個實體具有某些功能? – monkeyUser