简体   繁体   中英

Symfony2 custom query in entity orm

In controller

 return $this->render(
                'FrontBundle:Default:search.html.twig',
                array(
                    'edition'     => $edition,       THIS ONE
                    'paginator'   => $pagination,
                    'array_ed_id' => $editions_search,
                    'array_he_id' => $heading_search,
                    'text'        => $text,
                    'seo'         => $seo,
                    'result'      => $result,
                    'testix'      => 10
                )
            );

in Twig i need custom query value.getCount to count rows

    {% for value in edition %}
    <label><label class="" for="front_form_edition_s_{{ value.getId }}">
{{ value.getName }}</label>{{value.getCount}}</label>

in Edition entity i add custom function:

use Doctrine\ORM\Query\ResultSetMapping;
..........................
class Edition {
..........................
    public function getCount()
    {

        $rsm = new ResultSetMapping();
        $query = $entityManager->createNativeQuery('select count(*) from advert_edition where edition_id= ?', $rsm);
        $query->setParameter(1, '16');

        $users = $query->getResult();
        return 10;
    }
}

But this doesn't work! :( Please tell me how i can do that.

If you don't have the "count" property in your object, then:

{{ value.getCount() }}

or if you have the count property and "getCount" is the only getter:

{{ value.count }}

For this case i found another solution, i created twig extension Count

public function countEdition($id)
{
     $connection = mysql_connect("localhost", "root", "", "Test") or die("Could not connect in CountExt: " . mysql_error());
     mysql_select_db('Express',$connection)or die("Could not connect in CountExt: " . mysql_error());
     $query="select count(*) from advert_edition where edition_id=$id";
     $result = mysql_query($query) or die('Bad query CountExt: ' . mysql_error());
     $count=mysql_fetch_row($result);
     return $count[0];
}

And in twig:

{% for value in edition %}
<label><label class="" for="front_form_edition_s_{{ value.getId }}">{{ value.getName }}</label>{{value.getId|count}}</label>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM