jeudi 26 novembre 2015

Laravel 5.1: SQL query 'where LIKE %word%word%word%' not working

Keep in mind I have minimal SQL experience, so I may be doing it all wrong.

I'm trying to set up search for a table but simply searching for the string a user enters is not ideal because though something may come up for "steve", if a user types "steve jobs story", nothing will match as it'll be looking for that whole string.

I tried to breack it down by exploding the string into an array and then imploding that and separating it with %'s, so a search like "steve jobs story" would be "steve%jobs%story", and with my query it would be "%steve%jobs%story%". When I try searching this, I get no error but the query finds nothing, whereas when I just type one word it works, so I'm guessing what I'm trying to do isn't allowed.

Can someone point me in the right direction? Here is my controller/model:

// Controller

$query = $request->get('q');

$explodedQuery = explode(" ", $query);
$newQuery = implode("%", $explodedQuery);

$articles = Article::isLikeTitle($newQuery)
                   ->isLikeBody($newQuery)
                   ->latest('published_at')
                   ->published()
                   ->paginate(10);

// Model

public function scopeIsLikeTitle($query, $q)
{
    return $query->where('title', 'LIKE', "%$q%");
}

public function scopeIsLikeBody($query, $q)
{
    return $query->where('body', 'LIKE', "%$q%");
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire