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

4

我目前正在尝试使用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

在我的控制器中,我试图根据一个字符串在那个表上运行搜索。
public function searchAction($pattern) 
{
    $repository = $this->getDoctrine()->getRepository('..:Style');
    $search = $repository->search($pattern);

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

然而,当我尝试执行代码时,出现了以下异常。
Undefined method 'search'. The method name must start with either findBy or findOneBy!

我是否正确生成了实体或者我明显还缺少什么?

顺便提一下,当我在生成后查看Entity/Style.php时,没有清晰的方法->search(),这个功能应该由Symfony在这里生成吗?


请注意,Symfony 2 中使用的默认Doctrine版本是2.x,并且通过 $this->getDoctrine() 获取的可能是Doctrine 2类而不是Doctrine 1类... - AdrienBrault
2个回答

6

search()不是Symfony2支持的函数。您正在查看Symfony 1.x文档,而Symfony2与Symfony 1.x非常不同,因此作为参考,您应该始终使用文档

在Symfony2中获取实体有几种方法。以下是一些示例:

  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
    }
    

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


我正在尝试执行搜索,类似于mysql fulltext的搜索功能。 - Steven Lu
我有同样的问题。我想使用WHERE子句在LONGTEXT/BLOB字段中进行搜索,但我无法为其添加索引。此外,我没有添加一些Apache插件(如Lucene)的可能性。 - Tom

2

你可以在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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接