数据库搜索使用原则和Symfony2

数据库搜索使用原则和Symfony2

本文介绍了数据库搜索使用原则和Symfony2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前正在尝试使用Symfony2和Doctrine进行简单搜索。类似的内容:

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

我目前有以下 YAML 文件设置来生成我的实体。它作为一个类正确生成我的类样式实体。

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);
}

但是,当我尝试执行代码时,我得到以下异常。 / p>

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?

在旁注中,当我看到我的 Entity / Style.php 生成后,没有明确的方法 - > search(),是由Symfony在这里生成的函数?

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?

推荐答案

p> search()不是Symfony2支持的功能。您正在查看Symfony 1.x文档,Symfony2与Symfony 1.x是完全不同的,所以作为参考,您应该始终使用。

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.

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

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


  1. 查找

  1. Find

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


  • DQL:

  • 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的教义指南:

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

    这篇关于数据库搜索使用原则和Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-26 07:26