【问题标题】:Database Searching Using Doctrine and Symfony2使用 Doctrine 和 Symfony2 进行数据库搜索
【发布时间】:2012-07-17 18:14:45
【问题描述】:

所以我目前正在尝试使用 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 中使用的默认学说版本是 2.x,并且您通过执行$this->getDoctrine() 得到的可能是学说 2 类而不是学说 1 类...

标签: symfony doctrine


【解决方案1】:

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

在 Symfony2 中有几种获取实体的方法。以下是几个例子:

  1. 查找

    $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 搜索功能。
  • 我也有同样的问题。我想使用 WHERE 子句搜索 LONGTEXT/BLOB 字段,但我无法为其添加索引。我也没有可能添加一些像 Lucene 这样的 Apache 插件。
【解决方案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();

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多