lundi 18 avril 2016

Laravel search logic issue

I am developing a search module in Laravel 5.1 that searches businesses along with their phone numbers (records).

Tables:- businesses(id, name, status) and records(id, business_id, number, note);

The search logic says, 1) Search the businesses table for any business "name" match. 2) If matches found, then search the "note" field from the records table of matched business using the same keywords. 3) If matches found in the records table as well, then return the businesses with their records.

Condition: If Step 2 returns zero records, then don't include the businesses matched in step 1 (to prevent the display of businesses with zero matched records).

Here is code from search function:-

$keywords = explode(" ", Request::get('keyword'));
$businesses = new App\Business;

foreach ($keywords as $name) {
    $businesses = $businesses->orWhere('name', 'like', "$name%");
}

$businesses = $businesses->whereHas('records', function ($query) use ($keywords) {
    $query->where('note', 'like', '%'.$keywords[0].'%');

    foreach ($keywords as $note) {
        $query->orWhere('note', 'like', "%$note%");
    }
});

$businesses = $businesses->with(['records' => function ($query) use ($keywords) {
    $query->where('note', 'like', '%'.$keywords[0].'%');

    foreach ($keywords as $note) {
        $query->orWhere('note', 'like', "%$note%");
    }
}]);

return $businesses->paginate($limit);

The above logic is working fine for searching but does not follow the condition.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire