我在 phpMyAdmin 本地主机上创建了一个数据库。我在 symfony 中设置了数据库配置并创建了学说映射器(实体)。现在我需要做的就是进行 SELECT
查询并从数据库中获取信息:
表名:配置文件 行数:1
Controller 代码:
...
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
}
关于PHP: Controller 中的 Symfony2 MySQL SELECT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866832/