简体   繁体   English

如何在带有Like的LIKE中使用数组以检索Laravel中雄辩的行

[英]How to use array with LIKE with whereIn to retrieve eloquent rows in Laravel

I have an array 我有一个数组

//dynamically generated. dynamic number of elements
$keywords = ['google', 'youlense'];

For a exactly matching values of $keywork mapping to row in content column, i can do following: 对于映射到内容列中的行的$keywork值完全匹配,我可以执行以下操作:

$result = \App\Table::where(function($query){
    $query->whereIn('content', $keywords);
});

and the result would be somewhat 结果会有点

select * from tables where content IN ('google', 'youlense');

but I want to use LIKE operator so the result may be like 但是我想使用LIKE运算符,所以结果可能像

select * from tables where content LIKE ('%google%', '%youlense%');

I know that is not allowed in mysql but can some one recommend a simple and clean technique to handle this 我知道这在mysql中是不允许的,但是有人可以推荐一种简单干净的方法来解决这个问题

You can simply use orWhere method for every keyword and it will equivalent for whereIn . 您只需为每个关键字使用orWhere方法,它将等同于whereIn The code will look like: 代码如下所示:

$result = \App\Table::where(function($query){
    $query->orWhere('content', 'LIKE', '%google%')
          ->orWhere('content', 'LIKE', '%youlense%')
          -> and so on;
});

$result = \App\Table::where(function($query) use($keywords){
    foreach($keywords as $keyword) {
        $query->orWhere('content', 'LIKE', "%$keywords%")
    }
});

Note: gotten query can work very slowly. 注意:查询可能会非常缓慢。

You can write a function that will basically do the following : 您可以编写一个基本上可以完成以下任务的函数:

public function searchByKeywords(array $keywords = array()){
    $result = \App\Table::where(function($query) use ($keywords){
         foreach($keywords as $keyword){
              $query = $query->orWhere('content', 'LIKE', "%$keyword%");
         }
         return $query;
    });
    return $result->get(); // at this line the query will be executed only
                           // after it was built in the last few lines
}

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

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