Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database Searching Using Doctrine and Symfony2

So I'm currently trying to perform a simple search using Symfony2 and Doctrine. Something similar to this: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/searching.html

I've currently got the following YAML file setup to generate my entities. It generates my class Style entity correctly as a class.

...\Style:
    type: entity
    table: styles
    id:
        id:
            type: integer
            generator:
                strategy: IDENTITY
    actAs:
        Searchable:
            fields: [title]
            batchUpdates: true
    fields:
        title:
            type: string
            length: 150
            unique: true

In my controller, I'm trying to run a search on that table based on a string.

public function searchAction($pattern) 
{
    $repository = $this->getDoctrine()->getRepository('..:Style');
    $search = $repository->search($pattern);

    return $this->outputize($search);
}

However, when I try executing the code, I get the following exception.

Undefined method 'search'. The method name must start with either findBy or findOneBy!

Am I generating my entities correctly or is there something I'm clearly missing?

On a side note, when I look at my Entity/Style.php after generating, there is no clear method ->search(), is the function supposed to be generated by Symfony here?

like image 725
Steven Lu Avatar asked Feb 20 '23 20:02

Steven Lu


2 Answers

search() is not a function supported in Symfony2. You're looking at the Symfony 1.x documentation, and Symfony2 is really different from Symfony 1.x so for reference, you should always use the doc.

There are several ways to fetch entities in Symfony2. Here are a few examples:

  1. Find

    $user = $this->getDoctrine()
        ->getRepository('UserBundle:User')
        ->find($user_id)
    ;
    
  2. DQL:

    $query = $em->createQuery(
        'SELECT b FROM YourBundle:Bid b WHERE b.property_id = :property_id ORDER BY b.amount DESC'
    )->setParameter('property_id', $property_id);
    try {
        $bids = $query->getResult();
    } catch (\Doctrine\Orm\NoResultException $e) {
        //Handle No Result Exception here
    }
    

Refer to the Doctrine guide for Symfony2 here: http://symfony.com/doc/current/book/doctrine.html

like image 95
Hyunmin Kim Avatar answered Mar 07 '23 13:03

Hyunmin Kim


Hello you can do it in symfony 3

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
                'SELECT p
                FROM AppBundle:Hotel p
                WHERE p.address like :location
                ORDER BY p.address ASC'
                )->setParameter('location','%'.$request->get('location').'%' );
$hotel = $query->getResult();
like image 22
Shridhar U Patil Avatar answered Mar 07 '23 13:03

Shridhar U Patil