Symfony2如何找到以指定字符开头的记录



如何找到以指定字符开头的记录?

例如:仅用户名以a

开头的用户

用户类

    <?php
    namespace DemoBundleEntity;
    use FOSUserBundleModelUser as BaseUser;
    use DoctrineORMMapping as ORM;
    /**
     * @ORMEntity
     * @ORMTable(name="fos_user")
     */
    class User extends BaseUser
    {
        /**
         * @ORMId
         * @ORMColumn(type="integer")
         * @ORMGeneratedValue(strategy="AUTO")
         */
        protected $id;
        /**
         * @ORMColumn(type="string", length=50)
         */
        protected $name;
        /**
         * @ORMColumn(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"的未定义方法 类Demobundle Controller DefaultController"

hi @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 Profiler栏中,然后转到数据库部分。查看生成的查询,然后尝试直接在数据库上运行。

使用QueryBuilder Like学说的Expr:

// Example - $qb->expr()->like('u.firstname', $qb->expr()->literal('Gui%'))
public function like($x, $y); // Returns ExprComparison 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();

相关内容

  • 没有找到相关文章

最新更新