本文介绍了如何在symfony2中查询条件为"like"的mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在symfony2应用程序中搜索用户

I need to search the users in my symfony2 app

如果用户在搜索框中输入字母并提交,则需要让用户以该字母开头.

If a user enter an alphabet in search box and submit then he need to get the users starting with that alphabet.

如何实现这一目标?下面的代码将获得我们在文本框中键入的确切用户.

How to achieve this?Below code will get the exact user that we type in textbox.

如何在此应用喜欢"查询

How to apply "like" query in this

我的操作代码

public function searchAction(Request $request)
{

    $fname = $request->query->get('fname');
    if(isset($fname)){
    $user = $this->get('doctrine.odm.mongodb.document_manager')
        ->getRepository('WishbotWebBundle:User')
        ->findByusername($fname);
         return $this->render('WishbotWebBundle:Default:search.html.twig',array('user'=>$user));

    }else{
        return $this->render('WishbotWebBundle:Default:search.html.twig');

    }
}

推荐答案

首先,让我们看一下MongoDB:使用regex可以通过定义一个regex来完成,如:

First of all, let's look at MongoDB: Searching with regex can be done by defining a regex, as explained here:

db.users.find({"username": /^a/})

通过定义正则表达式,可以在php中完成同样的操作,这里:

The same can be done in php by defining a regex, explained here:

$collection->find(array('name'=> array('$regex' => '^a'));

您可以在Doctrine MongoDB ODM中使用几乎完全相同的regex语法:

You can use the almost exact same regex syntax with the Doctrine MongoDB ODM:

$user = $this->get('doctrine.odm.mongodb.document_manager')
        ->getRepository('WishbotWebBundle:User')
        ->findByUsername(array('$regex' => $fname));

请注意,即使只找到一个文档,也会返回一组文档.上面的正则表达式还匹配用户名在任何地方都包含$fname字符串的所有文档.

Please note that a collection of documents is returned, even if only one is found. The regex above also matches all documents where the username contains the $fname string anywhere.

如果要以$fname开头的用户名,则需要使用'^' . $fname.

If you want usernames which start with the $fname, you need to use '^' . $fname.

这篇关于如何在symfony2中查询条件为"like"的mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:50