RSAdmin
RSAdmin

Reputation: 589

Multiple OR terms in WHERE clause

Ii am building a poor-man's search engine for in-house use. Back when I was doing this sort of thing using MySQLi or a pgsql db in code, I would write something along the lines of this:

$sql = "SELECT * FROM $table ";
$WC = array();
foreach($columns as $col )
{
  $WC[] = $col ." like '%".$term."%'";
}
$sql .= ' WHERE ('. implode(') OR (', $WC). ')';

return $sql;

which would concatenate a number (unknown) of column names with the search term. The resulting SQL looking somewhat like this:

SELECT * FROM books WHERE (title like '%kids%') OR (publisher like '%kids%') OR (author like '%kids%');

Fairly crude but effective to a point. Having a small and well known data set allows this sort of thing to be quite useful.

However...

I cannot for the life of me figure out how to append an arbitrary number of OR clauses to a DB::table('books')-> ... construct. Documentation completely skirts this sort of construction. Can anyone point me in the right direction?

Upvotes: 0

Views: 51

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219930

Just call orWhere repeatedly on the query object:

$query = DB::table('books');

foreach ($columns as $column)
{
    $query->orWhere($column, 'like', "%{$term}%");
}

return $query;

Upvotes: 1

Zerquix18
Zerquix18

Reputation: 769

You should better use MATCH AGAINST for that search.

Upvotes: 0

Related Questions