简体   繁体   English

多列多词搜索Symfony主义

[英]Multi word search on multiple columns Symfony Doctrine

I am trying to craft a multiword search that will query multiple columns in a table. 我试图制作一个多字搜索,将查询表中的多个列。 My code works great thus far for a single column, but as you can imagine using it for more then one column becomes an issue. 到目前为止,我的代码对单个列的效果很好,但是正如您可以想象的那样,将其用于更多列会成为一个问题。

If I add orWhere it won't work, and I don't really want to create more for loops because it will become quite cumbersome. 如果我添加orWhere不会起作用,并且我真的不想创建更多的for循环,因为它将变得非常麻烦。 Any Ideas? 有任何想法吗?

$query = $request->getParameter("article-search");
$keywords = explode(" ", $query);

for( $i = 1; $i <= count( $keywords ); $i++ ){
    $q->addWhere("a.title LIKE ?", "%" . $keywords[$i - 1] . "%");
}

I just did it like this.. Maybe it helps somebody.. 我就是这样做的。也许对某人有帮助。

$now = "some other parameter";

$parts = explode(" ",trim($searchtext));
$clauses=array();
// static paramtter setted here
$parameters = array(
    ':now' => $now
);

$i = 0;
foreach ($parts as $part){
    // for every word make new search query and parameter
    $parameters[":param".$i] = "%".$part."%";
    if($i == 0){
        $clauses  = "v.description LIKE :param".$i." OR v.name LIKE :param".$i." OR v.sale LIKE :param".$i;
    } else {
        $clauses .= " OR v.description LIKE :param".$i." OR v.name LIKE :param".$i." OR v.sale LIKE :param".$i;
    }
    $i ++;
}

$qb->select('v')
    ->from('MyBundle\Entity\Voucher', 'v')
    ->where('v.date_start <= :now')
    ->andWhere('v.date_end >= :now')

    ->andWhere($clauses)
    ->setParameters($parameters);

Usually I would write this as a query that looks something like the following: 通常,我会将其编写为查询,如下所示:

$query = "`where column like '%$keywordOne%' or column like '%keywordTwo%'`";

Though I'm not sure how you implement that with the query-building tool you have there. 尽管我不确定您如何使用查询构建工具来实现该功能。

Here's a quick example that might help build the where portion of the query using the array of keywords you have: 这是一个简单的示例,可能有助于使用您拥有的关键字数组来构建查询的where部分:

<?php
$keywords = array("bing", "bang", "jump");

$query_start = 'where colummName';
$like_portion = "like '%" . implode("%' or columnName like '%", $keywords) . "%'";

if(sizeof($keywords) > 0) {
    echo "`$query_start $like_portion`";
} else {
    // No keywords
}
?>

Let me know if there's anything I can clarify here 让我知道是否可以在这里澄清

Maybe you can consider using "union"? 也许您可以考虑使用“联盟”? Also, for such complex queries, I would use native SQL instead of ORM practice. 此外,对于此类复杂的查询,我将使用本机SQL代替ORM练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM