搜索多个字段(DQL).如何添加一个条件,如果一个NULL字段是由形式返回?



在我的Symfony项目中,我有一个搜索表单,有5个字段来过滤用户。

  • 一个文本字段(用户名)和4个选择字段(类别、城市、邮政编码和位置)。

如果所有的字段都填满了,一切都很完美,但我想添加一个条件(在存储库中,搜索类型或控制器),以避免发送类似"→引入("p。nom LIKE NULL')"例如,如果表单发送的变量$nomPrestataire的值为"NULL"

我的查询生成器:

public function SearchBar($nomPrestataire, $categorieId, $localite, $codePostal, $commune): ?array
{
return $this->createQueryBuilder('p')
->andWhere('p.nom LIKE :nom')
->andWhere('proposer = :categorieId')
->andWhere('user.codePostal = :cp')
->andWhere('user.commune = :com')
->andWhere('user.localite = :loc')
->leftJoin('p.proposer', 'proposer')
->leftJoin('p.utilisateur', 'user')
->setParameter('nom', '%'.$nomPrestataire.'%' )
->setParameter('categorieId', $categorieId)
->setParameter('cp', $codePostal)
->setParameter('com', $commune)
->setParameter('loc' , $localite)
->orderBy('p.nom', 'ASC')
->getQuery()
->getResult();
;
}

My form builder:

class PrestataireSearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('prestataire',TextType::class, [
'required' => false,
'attr' =>[
'placeholder' => 'Saisissez un nom',
]
])
->add ('localite', EntityType::class,[
'class' => Localite::class,
'required' => false
])
->add ('categorie', EntityType::class,[
'class' => CategorieService:: class,
'constraints' => [
new NotBlank()
]
])
->add ('cp', EntityType:: class,
[
'class' => CodePostal::class,
'required' => false
])
->add ('commune', EntityType::class, 
[
'class' => Commune:: class,
'required'=> false
])
->add('recherche', SubmitType::class, 
['label' => 'Rechercher']
)
;
}

非常感谢您的帮助!
  • 我已经尝试了几个'Not Null'语法在我的queryBuilder,但没有工作。
  • 我查看了文档:https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/reference/query-builder.html

我终于自己弄明白了😅

我必须修改存储库中的查询以使用if()条件。现在,无论我是否填充每个字段,它都可以工作。

public function SearchBar($nomPrestataire, $categorieId, $localite, $codePostal, $commune): ?array{
$query = $this->createQueryBuilder('p')
// liaison prestataire-catégorie 'proposer' via les Id
->join('p.proposer', 'proposer')
->join('p.utilisateur', 'user')
;
if($nomPrestataire){
$query->andWhere('p.nom LIKE :nom')
->setParameter('nom', '%'.$nomPrestataire.'%');
}
if($categorieId){
$query->andWhere('proposer = :categorieId')
->setParameter('categorieId', $categorieId);
}
if($localite){
$query->andWhere('user.localite = :loc')
->setParameter('loc' , $localite);
}
if($codePostal){
$query->andWhere('user.codePostal = :cp')
->setParameter('cp', $codePostal);
}
if($commune){
$query->andWhere('user.commune = :com')
->setParameter('com', $commune);
}
$query->orderBy('p.nom', 'ASC');
$query = $query->getQuery();
return $query->getResult();
;
}

最新更新