如何查找以指定字符开头的记录?
例如:只有用户名以A
开头的用户用户类
<?php
namespace DemoBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=50)
*/
protected $name;
/**
* @ORM\Column(type="string", length=50)
*/
protected $lastname;
public function __construct()
{
parent::__construct();
// your own logic
}
//getters and setters
}
和解决方案@Kwido的控制器操作
public function listAction($letter)
{
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder
->select(['user'])
->from(User::class, 'user')
->andWhere($queryBuilder->expr()->like('user.lastname', ':lastname'))
->setParameter('lastname', $queryBuilder->expr()->literal('A%'));
$result = $queryBuilder->getQuery()->getResult();
die(var_dump($result));
}
这就是我所拥有的一切。这给了我错误
尝试调用名为“getEntityManager”的未定义方法 class DemoBundle \ Controller \ DefaultController“
答案 0 :(得分:1)
您好@Damian将您的代码更改为。
public function listAction($letter)
{
$result = $this->getDoctrine()
->getManager()
->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->where('u.lastname LIKE :lastname')
->setParameter('lastname', 'A%')
->getQuery()
->getResult();
dump($result);
// return response bellow
}
加载页面后,单击Symfony探查器栏并转到数据库部分。查看生成的查询并尝试直接在数据库上运行它。
答案 1 :(得分:0)
使用Doctrine的querybuilder Like
expr:
// Example - $qb->expr()->like('u.firstname', $qb->expr()->literal('Gui%'))
public function like($x, $y); // Returns Expr\Comparison instance
要在存储库类中使用Like
表达式:
// getEntityManager() = $this->getDoctrine()->getManager();
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder
->select(['user'])
->from(User::class, 'user')
->andWhere($queryBuilder->expr()->like('user.userName', ':userName'))
->setParameter('userName', $queryBuilder->expr()->literal('A%'));
$result = $queryBuilder->getQuery()->getResult();