Created
February 16, 2013 16:43
-
-
Save clouddueling/4967617 to your computer and use it in GitHub Desktop.
search table with like using eloquent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static function search_contacts($terms) | |
{ | |
$search_all = ! Input::has('first') && ! Input::has('last'); | |
$terms = escape($terms); | |
$search_terms = explode(' ', $terms); | |
$search_term_bits = array(); | |
foreach ($search_terms as $term) { | |
$term = trim($term); | |
if (! empty($term)) { | |
if ((Input::has('first') && Input::has('last')) || $search_all) | |
$search_term_bits[] = "`first` LIKE '{$term}%' OR `last` LIKE '{$term}%'"; | |
if (Input::has('first') && ! Input::has('last')) | |
$search_term_bits[] = "`first` LIKE '{$term}%'"; | |
if (! Input::has('first') && Input::has('last')) | |
$search_term_bits[] = "`last` LIKE '{$term}%'"; | |
} | |
} | |
$contacts = Contact::raw_where("(" . implode(' AND ', $search_term_bits) . ")") | |
->raw_where("`account_user_id`=?", array(Auth::user()->account_user_id)) | |
->where_deleted(0) | |
->take(20) | |
->get(); | |
$contacts_array = array(); | |
foreach ($contacts as $contact) { | |
$new_contact = $contact->to_array(); | |
$new_contact['rank'] = levenshtein($terms, $contact->first . ' ' . $contact->last); | |
$contacts_array[] = $new_contact; | |
} | |
aasort($contacts_array, 'rank'); | |
return $contacts_array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment