使用Doctrine和Symfony2进行数据库搜索

Ste*_* Lu 4 doctrine symfony

所以我目前正在尝试使用Symfony2和Doctrine进行简单的搜索.与此类似的东西:http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/searching.html

我目前有以下YAML文件设置来生成我的实体.它class Style作为一个类正确地生成我的实体.

...\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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我正在尝试基于字符串在该表上运行搜索.

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

    return $this->outputize($search);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试执行代码时,我得到以下异常.

Undefined method 'search'. The method name must start with either findBy or findOneBy!
Run Code Online (Sandbox Code Playgroud)

我是否正确地生成了我的实体,或者是否有一些我明显缺失的东西?

另一方面,当我看到我Entity/Style.php生成后,没有明确的方法->search(),这个函数应该由Symfony在这里生成吗?

Hyu*_*Kim 6

search()不是Symfony2中支持的功能.您正在查看Symfony 1.x文档,Symfony2与Symfony 1.x真的不同,所以为了参考,您应该始终使用doc.

有几种方法可以在Symfony2中获取实体.这里有一些例子:

  1. $user = $this->getDoctrine()
        ->getRepository('UserBundle:User')
        ->find($user_id)
    ;
    
    Run Code Online (Sandbox Code Playgroud)
  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
    }
    
    Run Code Online (Sandbox Code Playgroud)

请参阅Symfony2的Doctrine指南:http://symfony.com/doc/current/book/doctrine.html