[英]PHP: Symfony2 MySQL SELECT query in controler
我在phpMyAdmin本地主機上創建了一個數據庫。 我已經在symfony中設置了數據庫配置,並創建了教義映射器(實體)。 現在,我需要做的是SELECT
查詢並從數據庫中獲取信息:
表名稱:個人資料行數:1
控制器代碼:
...
use Ignas\IgnasBundle\Entity\Profilis;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
$profilis = new Profilis();
return new Response('Id '.$profilis->getId());
}
}
getId
方法來自Entity/Profilis
文件Profilis
類。
有沒有簡單的方法可以做到這一點? 我搜索了一會兒,我所能找到的就是根本不熟悉的教義語法。
您可以通過不同的方式來做到這一點:
首先,在您的Controller
獲取EntityManager
$em = $this->getDoctrine()->getEntityManager();
萬一它說它被棄用了,你也可以像這樣得到它:
$em = $this->getDoctrine()->getManager();
那么您可以使用QueryBuilder
或createQuery
方法
使用Select方法(如注釋中所建議)
$profilis= $em->select('p.id')
->from('BundleName:EntityName', 'p')
->getQuery()
->getResult();
簡單查詢 :
$query = $em->createQuery("SELECT * FROM Profilis p");
$profilis = $query->getResult();
注意
這兩個方法都返回一個Profilis
數組,因此您可以簡單地以這種方式循環它們:
foreach($profilis as $p){
// do whatever you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.