一、先声明一个实体管理器
$entityManager = $this->getDoctrine()->getEntityManager();
$respority = $entityManager->getRepository("AcmeDemoBundle:SymfonyUse");
格式 : AcmeDemoBundle:SymfonyUse (所属bundle:实体类)
二、常用方法之findAll()、findOneBy()、findBy()
1、findAll() 取所有实体
$entitys = $respority->findAll();
2、findOneBy() 根据条件获取一个实体
$entitys = $respority->findOneBy(array('name'=>'D&Luf' ));获取单一实体,这里是获取name为D&Luf的实体
其中name对应yml文件里的字段名如:
name:
type: string
length: 20
fixed: false
nullable: true
3、findBy() 根据条件获取实体
$entitys = $respority->findBy(array('name'=>'D&Luf' ),array('telephone'=>'ASC'));
$entitys = $respority->findBy(array('name'=>'D&Luf' ),array('telephone'=>'ASC'),$size,$start);
第一个数组是字段过滤,第二数组是排序。$size是取得条数,$start是起始位置,可以用于分页。
返回值,打印为
Array ( [0] => Acme\DemoBundle\Entity\SymfonyUse Object (
[id:Acme\DemoBundle\Entity\SymfonyUse:private] => 1
[name:Acme\DemoBundle\Entity\SymfonyUse:private] => D&Luf
[message:Acme\DemoBundle\Entity\SymfonyUse:private] => Luf
[telephone:Acme\DemoBundle\Entity\SymfonyUse:private] => 123456 ) )
三、直接sql语句方式,获取数据
$pdo = $entityManager->getConnection();
$sql = "select * from symfony_use";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$entitys = $stmt->fetchAll();
返回值,打印为
Array ( [0] => Array ( [id] => 1 [0] => 1 [name] => D&Luf [1] => D&Luf [message] => Luf [2] => Luf [telephone] => 123456 [3] => 123456 )
[1] => Array ( [id] => 2 [0] => 2 [name] => HELLO [1] => HELLO [message] => Hello [2] => Hello [telephone] => 234567 [3] => 234567 ) )