Symfony的。存储库方法。在查询参数(queryBuilder)中绑定用户

问题描述 投票:0回答:1

我有一个问题,我是symfony 3.2中的新手我想根据用户登录查询一个对象。我听说我需要注入用户信息?但是怎么样?

知识库

public function findAllActiveCategoryByUser(UserInterface $user)
{
    return $this->createQueryBuilder('sc')
        ->andWhere('sc.company_id = :company')
        ->setParameter('company_id', $this->getUser->getCompany->getCompanyId)
        ->orderBy('sc.createdAt', 'ASC');
}

SubAgentType

public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
             ->add('category', EntityType::class, [
            'placeholder' => 'Choose Category',
            'class' => Sub_agent_category::class,
            'query_builder' => function (Sub_agent_categoryRepository $er) {
                return $er->findAllActiveCategoryByUser();

            },
            'constraints' => array(new NotBlank(array('message' => 'Category is required.')))
        ])
symfony doctrine-orm
1个回答
-1
投票

试试这个:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $user = $this->securityContext->getToken()->getUser();

    $builder
        ->add('company', EntityType::class, [
            'placeholder' => 'Choose Company',
            'class' => Company::class,
            'query_builder' => function (CompanyRepository $er) {
                return $er->findAllActiveCompany($user);
            },
            'constraints' => array(new NotBlank(array('message' => 'Company is required.')))
        ])
}

库:

public function findAllActiveCategoryByUser(UserInterface $user)
{
    $qb = $this->createQueryBuilder('sc');
    $result = $qb->select('sc')
        ->where('sc.company_id = :company')
        ->setParameter('company', $this->getUser->getCompany->getCompanyId)
        ->orderBy('sc.createdAt', 'ASC')
        ->getQuery();
    return $result->getResult();

}

© www.soinside.com 2019 - 2024. All rights reserved.