Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my SQL query search several words in the sentence even if they do not follow each other

I have a SQL query for my search form.

$term = $request->get('term');

$queries = Article::where('title', 'LIKE', '%' . $term . '%')->published()->get();

My research is working. If I have an article called "my great article is awesome" and that I write in my search form "greate article" it works.

But if I write "article awesome", the words do not follow each other, and it does not work.

How do I get my query to work just with keywords?

Thank you

like image 598
Jeremy Avatar asked May 17 '17 23:05

Jeremy


People also ask

How can I get certain words from a string in SQL?

Use the SUBSTRING() function. The first argument is the string or the column name. The second argument is the index of the character at which the substring should begin. The third argument is the length of the substring.

Which operator is used to match the text while search in SQL query?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

Is there a Contains function in SQL?

CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types. CONTAINS can search for: A word or phrase. The prefix of a word or phrase.


1 Answers

You can do something like follows:

$term = $request->get('term');
$keywords = explode(" ", $term);

$article = Article::query();
foreach($keywords as $word){
    $article->orWhere('title', 'LIKE', '%'.$word.'%');
}

$articles = $article->published()->get();

If you want only results that contain all the words in the query just replace the orWhere with where.

If you want to filter out certain words you could add something like:

$filtered = ["a", "an", "the"];
$filteredKeywords = array_diff($keywords, $filtered);

Alternatively you can pass a closure if you want to be more dynamic:

$filteredKeywords = array_filter($keywords, function($word) {
    return strlen($word) > 2;
});
like image 115
Alex Harris Avatar answered Sep 22 '22 11:09

Alex Harris