Symfony2 / Doctrine:SQL到DQL,用于在存储库中创建搜索表单的querybuilder [英] Symfony2/Doctrine: SQL to DQL for a querybuilder in a repository to make a search form

查看:107
本文介绍了Symfony2 / Doctrine:SQL到DQL,用于在存储库中创建搜索表单的querybuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我与Symfony的项目中,我需要用多准则制作搜索表单。
我有一个选择的实体Parc,一个选择的实体Typesactivite和一个输入文本的Ensembles。



我有这个 SQL 请求:

  SELECT distinct e.nom FROM`ensembles` e,`parcsimmobilier` p,`batiments` b, batiments_typesactivite` bta,`typesactivite` ta WHERE e.parcsimmobilier_id = p.id AND b.ensembles_id = e.id AND bta.batiments_id = b.id AND bta.typesactivite_id = ta.id AND p.nom =Ville de Dijon AND ta.type =Sport

这个SQL请求给了我所有属于第戎parc的合奏我的尝试在我的EnsemblesRepository.php中以 DQL 语法转换这个SQL请求,但是它并没有给出我的意思。



好的结果,我想我做错了:

  public function recherche($ input)// $ input est la valeurentrée dans l'input type text recherche 
{
$ qb = $ this - > createQueryBuil ('e')
- > select('e.nom')
- > addSelect('e.parcsimmobilier')
- > from('MySpaceDatabaseBundle:Parcsimmobilier' ,'p')
- > from('MySpaceDatabaseBundle:Typesactivite','ta')
- > from('MySpaceDatabaseBundle:Batiments','b')
- >其中('e.parcsimmobilier = p.id')
- > andWhere('b.ensembles = b.id')
- > andWhere('ta.batiments = b.id')
- > andWhere('e.nom LIKE:input')
- > setParameters(array(
'input'=> % $输入 %))。;

return $ qb-> getQuery() - > getResult();
}

当我提交表单时,我有以下错误:


[2/2] QueryException:[语义错误]行0,col 16附近
'parcsimmobilier':错误:无效的PathExpression。必须是
StateFieldPathExpression。



[1/2] QueryException:SELECT e.nom,e.parcsimmobilier FROM
MySpace\DatabaseBundle\ Entity\Enembles e,
MySpaceDatabaseBundle:Parcsimmobilier p,
MySpaceDatabaseBundle:Typesactivite ta,
MySpaceDatabaseBundle:Batiments b WHERE e.parcsimmobilier = p.id AND
b.ensembles = b .id AND ta.batiments = b.id AND e.nom LIKE:input


如何使DQL请求在我的存储库中?



这是我提交的搜索表单,用于在我的实体上进行搜索集合:

  class RechercheType extends AbstractType 
{
/ **
* @param FormBuilderInterface $ builder
* @param array $ options
* /
public function buildForm(FormBuilderInterface $ builder,array $ options)
{
$ builder
// Parcsimmobilier
- > add('parcs :,实体,阵列(
‘类’=> 'MySpaceDatabaseBundle:Parcsimmobilier',
'property'=> NOM,
empty_value => 'Choisir le parc immobilier',
'required'=> true))

// Typesactivite
- > add('typesactivite:','entity',array(
'class'=>'MySpaceDatabaseBundle:Typesactivite'
'property'=>'type',
'empty_value'=>'Choisir le type d\'activite',
'required'=> false))

// Ensembles
- > add('ensemble','text',array(
'attr'=> array('placeholder'=>'rechercher') ,
'required'=> false))
;






更新 p>

有我的代码为控制器,如果可以帮助:

  public function rechercheEnsemblesAction(){

$ formRecherche = $ this-> createForm(new RechercheType());

// si laméthodeest bien en POST
if($ this-> get('request') - > getMethod()=='POST')
{
$ formRecherche-> bind($ this-> get('request'));
$ em = $ this-> getDoctrine() - > getManager();
$ ensemble = $ em - > getRepository('MySpaceDatabaseBundle:Ensembles')
- > recherche($ formRecherche ['ensemble']
- > getdata());

}

return $ this-> render('MySpaceGestionPatrimoinesBundle:Ensembles:rechercheEnsembles.html.twig',array('ensemble'=> $ ensemble,'formRecherche '=> $ formRecherche-> createView()));
}

让我们尝试做查询



选择标签中,我可以选择名称需要的表单中),在输入文本中输入名称为合奏的值。
我的 SQl 请求位于 phpMyAdmin

  SELECT distinct e.nom FROM`ensembles` e,`parcsimmobilier` p where e.parcsimmobilier_id = p.id 

此请求使我属于 parc与id 1 所有合奏



,我在我的存储库中尝试这个功能 EnsemblesRepository.php

  public function recherche )// $ input est la valeurentréedans l'input type text recherche 
{
$ qb = $ this - > createQueryBuilder('e')
- > select('e $'
- > from('MySpaceDatabaseBundle:Parcsimmobilier','p')
- >其中('e.parcsimmobilier = p.id')
- >和('e.nom LIKE:input')
- > setParameters(array(
'input'=>%。$ input。%));

return $ qb-> getQuery() - > getResult();

}

但它并没有给我带来好的结果。结果是我的数据库中的所有Ensemble,即使我在我的选择标签中选择了一个parc,在我的buildform中创建。



有人可以帮助我一步一步吗?

如果您需要更多信息,这是我的实体之间的关系。只有两个类/实体有我需要的关系。



Ensemnles.php

  / ** 
* @var \Parcsimmobilier
*
* @ ORM\ManyToOne(targetEntity =Parcsimmobilier)
* @ ORM\JoinColumns({
* @ ORM\JoinColumn(name =parcsimmobilier_id,referencedColumnName =id)
*})
* /
private $ parcsimmobilier;

Batiments.php

  / ** 
* @ ORM\ManyToOne(targetEntity =MySpace\DatabaseBundle\Entity\Enembembles)
* @ORM \JoinColumn(nullable = false)
* /
private $ ensemble;

/ **
* @ ORM\ManyToMany(targetEntity =MySpace\DatabaseBundle\Entity\Typesactivite)
* @ ORM\JoinColumn(nullable = true)
* /
private $ typesactivite;

我真的找不到解决方案,如果需要,请不要犹豫要求更多的信息。



感谢您的理解。

解决方案

这里,如果要在Symfony中管理您的实体,请查看Jquery数据表此处



然后,您可以使用自己的请求与Jquery,Ajax和Symfony在html < table>中的搜索表单中获得一些结果。



这是一个 .js 的示例,您可以在datatable :$($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ {
dom:'<toolbar> frtip',
response:true,
initComplete:function(){
var api = this.api();
api.columns()。indexes()。flatten()。each(function(i){
var column = api.column(i);
var select = $(' ; $< / option>< / select>')
.appendTo($(column.footer())。empty())
.on ('change',function(){
var val = $ .fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val?'^'+ val +'$':'',true,false)
.draw();
});
column.data()。 unique()。sort()。each(function(d,j){
select.append('< option value ='+ d +'>'+ d +'< / option>')
});
});
}
});
$(div.toolbar)。html('< b>示例< / b>');
});

当然, html (don' t使用DataTables忘记一个表的结构,所有步骤都在doc =>中,为了能够增强一个HTML表,表必须是有效的,格式良好的HTML,带有一个标题(thead)和一个body(tbody)。也可以使用可选的页脚(tfoot)。):

 < table id =dataTablesclass =您的类或引导类,如果您使用引导例如> 
< thead>
< tr>
< th>列1< / th>
< th>列2< / th>
...你想要的号码...
< / tr>
< / thead>
< tbody>
< tr>
< td> {{entity.field}}< / td>
< td> {{entity.field2}}< / td>
... etc ..
< / tr>
< / tbody>
< / table>


In my project with Symfony, I need to make a search form with multicriteria. I have a select for the entity Parc, a select for the entity Typesactivite and an input text for Ensembles.

I have this SQL request:

SELECT distinct e.nom FROM `ensembles` e, `parcsimmobilier` p, `batiments` b, `batiments_typesactivite` bta, `typesactivite` ta WHERE e.parcsimmobilier_id=p.id AND b.ensembles_id=e.id AND bta.batiments_id=b.id AND bta.typesactivite_id = ta.id AND p.nom="Ville de Dijon" AND ta.type="Sport"

This SQL request gives me all ensembles which belong to the Dijon parc where the batiments have Sport for activity.

I tried to transform this SQL request in DQL syntax in my EnsemblesRepository.php but it not gives me the good result, I think I do it wrong:

public function recherche($input) //$input est la valeur entrée dans l'input type text recherche
    {
        $qb = $this ->createQueryBuilder('e')
                    ->select('e.nom')
                    ->addSelect('e.parcsimmobilier')
                    ->from('MySpaceDatabaseBundle:Parcsimmobilier', 'p')
                    ->from('MySpaceDatabaseBundle:Typesactivite', 'ta')
                    ->from('MySpaceDatabaseBundle:Batiments', 'b')
                    ->where('e.parcsimmobilier = p.id')
                    ->andWhere('b.ensembles=b.id')
                    ->andWhere('ta.batiments=b.id')
                    ->andWhere('e.nom LIKE :input')
                    ->setParameters(array(
                        'input' => "%".$input."%"));

        return $qb->getQuery()->getResult();
    }

When I submit the form, I have these errors:

[2/2] QueryException: [Semantical Error] line 0, col 16 near 'parcsimmobilier': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

[1/2] QueryException: SELECT e.nom, e.parcsimmobilier FROM MySpace\DatabaseBundle\Entity\Ensembles e, MySpaceDatabaseBundle:Parcsimmobilier p, MySpaceDatabaseBundle:Typesactivite ta, MySpaceDatabaseBundle:Batiments b WHERE e.parcsimmobilier = p.id AND b.ensembles=b.id AND ta.batiments=b.id AND e.nom LIKE :input

How can I make the DQL request in my repository?

This is the search form I submit for make a search on my entity Ensembles:

class RechercheType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //Parcsimmobilier
            ->add('parcs:', 'entity', array(
                'class' => 'MySpaceDatabaseBundle:Parcsimmobilier', 
                'property' => 'nom', 
                'empty_value' => 'Choisir le parc immobilier', 
                'required' => true))

            //Typesactivite
            ->add('typesactivite:', 'entity', array(
                'class' => 'MySpaceDatabaseBundle:Typesactivite', 
                'property' => 'type', 
                'empty_value' => 'Choisir le type d\'activite', 
                'required' => false))

            //Ensembles
            ->add('ensemble', 'text', array(
                'attr' => array('placeholder' => 'rechercher'), 
                'required' => false))
            ;


UPDATE

There is my code for the controller, if it could helps:

public function rechercheEnsemblesAction() {

        $formRecherche = $this->createForm(new RechercheType());

        //si la méthode est bien en POST
        if ($this->get('request')->getMethod() == 'POST' ) 
        {
            $formRecherche->bind($this->get('request'));
            $em=$this->getDoctrine()->getManager();
            $ensemble = $em ->getRepository('MySpaceDatabaseBundle:Ensembles')
                            ->recherche($formRecherche['ensemble']
                            ->getdata());

        }

        return $this->render('MySpaceGestionPatrimoinesBundle:Ensembles:rechercheEnsembles.html.twig', array('ensemble' => $ensemble, 'formRecherche' => $formRecherche->createView() ));
    }

Let's try to do the query step by step.

In a select tag, I can choose the name of the parcs (required in my form), without enter a value in my input text for the name of ensemble. My SQl request is on phpMyAdmin:

SELECT distinct e.nom  FROM `ensembles` e, `parcsimmobilier` p where e.parcsimmobilier_id=p.id

This request gives me all ensembles belonging to the parc with id 1.

In DQl, I try this in my repository EnsemblesRepository.php:

public function recherche() //$input est la valeur entrée dans l'input type text recherche
{
    $qb = $this ->createQueryBuilder('e')
                ->select('e.nom')
                ->from('MySpaceDatabaseBundle:Parcsimmobilier', 'p')
                ->where('e.parcsimmobilier = p.id')
                ->andWhere('e.nom LIKE :input')
                ->setParameters(array(
                    'input' => "%".$input."%"));

    return $qb->getQuery()->getResult();

}

But it doesn't return me the good result. The result is all Ensemble in my database even if I choose a parc in my select tag create in my buildform.

Someone could help me step by step?

If you need more information, this the relation between my entities. Only two classes/entities have the relation I need.

Ensemnles.php:

/**
     * @var \Parcsimmobilier
     *
     * @ORM\ManyToOne(targetEntity="Parcsimmobilier")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parcsimmobilier_id", referencedColumnName="id")
     * })
     */
    private $parcsimmobilier;

Batiments.php:

/**
 * @ORM\ManyToOne(targetEntity="MySpace\DatabaseBundle\Entity\Ensembles")
 * @ORM\JoinColumn(nullable=false)
 */
private $ensembles;

/**
 * @ORM\ManyToMany(targetEntity="MySpace\DatabaseBundle\Entity\Typesactivite")
 * @ORM\JoinColumn(nullable=true)
 */
private $typesactivite;

I really can't find the solution, do not hesitate to ask for more informations if you need.

Thank you for your comprehension.

解决方案

Like I told you here, check the Jquery datatables here, for your project if it's to manage your entities in Symfony.

Then, you can use your own request with Jquery, Ajax and Symfony to have some results for a search form in an html <table>.

This is an example of .js you can use for search in datatable:

$(document).ready(function() {
    $('#dataTables').DataTable( {
        "dom": '<"toolbar">frtip',
        responsive: true,
        initComplete: function () {
            var api = this.api();
            api.columns().indexes().flatten().each( function ( i ) {
                var column = api.column( i );
                var select = $('<select><option value=""></option></select>')
                    .appendTo( $(column.footer()).empty() )
                    .on( 'change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        column
                            .search( val ? '^'+val+'$' : '', true, false )
                            .draw();
                    });
                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                });
            });
        }
    });
    $("div.toolbar").html('<b>Example</b>');
});

And of course the html (don't forget the structure for a table using DataTables, all step are in the doc => For DataTables to be able to enhance an HTML table, the table must be valid, well formatted HTML, with a header (thead) and a body (tbody). An optional footer (tfoot) can also be used.):

<table id="dataTables" class="your class or bootstrap class if you are using bootstrap for example">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            ...number you want...
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>{{ entity.field }}</td>
            <td>{{ entity.field2 }}</td>
            ...etc..
        </tr>
    </tbody>
</table>

这篇关于Symfony2 / Doctrine:SQL到DQL,用于在存储库中创建搜索表单的querybuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆