2017-09-25 53 views
0

我有一個搜索行用戶輸入查詢分爲逗號。我需要在SQL表中至少找到1個匹配項。但我需要在每個找到的對象中標記匹配。我怎樣才能做到這一點?如何查看SQL中的搜索匹配?

工作搜索(Laravel佞(PostgreSQL的)無標識的匹配):

public function searchOfAuthor(Request $request) 
{ 
    $search = array_map('trim', explode(',', $request->get('search'))); 

    $columns = [ 
     'city', 
     'phone', 
     'email', 
     'skype', 
     'icq', 
     'vk' 
    ]; 

    $authors = AuthorMask::where(function ($query) use ($columns, $search) { 
      foreach ($search as $searchKey) { 
       if (!empty($searchKey)) { 
        $query->orWhere('name', 'ILIKE', '%'.$searchKey.'%'); 
        foreach ($columns as $column) { 
         $query->orWhere($column, 'ILIKE', $searchKey); 
        } 
       } 
      } 
     }) 
     ->with('author') 
     ->orderByRaw('company_id = ? desc', Auth::user()->company_id) 
     ->paginate(5); 

    if (empty($authors->items())) { 
     return response()->json([ 
      'data' => null, 
      'error' => 'Authors Have Not Been Found' 
     ], 404); 
    } 

    return response()->json([ 
     'data' => [ 
      'authors' => $authors 
     ], 
     'error' => null 
    ], 200); 
} 

對不起,我的英語水平。

+0

嘿,如果你尋找到高級搜索功能,你應該看看Laravel偵察員:http://laravel.com/docs/5.5/scout –

+0

@JulienBourdeau嗨!我嘗試過偵察兵,但對我來說這不起作用(與Algolia Driver一起使用)。通過指令安裝,搜索查詢顯示在Algolia網站上,但返回爲空。 Idk爲什麼。 –

+0

如果您願意再試一次,請告訴我,我可以幫助您。你可以在discourse.algolia.com上發帖(我在監視Laravel的問題),或者在SO上發帖。 –

回答

0

在laravel或Mysql中沒有像ILIKE這樣的條件。應該有LIKE。有兩行代碼有ILIKE

$query->orWhere('name', 'ILIKE', '%'.$searchKey.'%');

$query->orWhere($column, 'ILIKE', $searchKey);

ILIKE上面兩行刪除I。從ILIKE取出I之後,它看起來應該像

$query->orWhere('name', 'LIKE', '%'.$searchKey.'%');

$query->orWhere($column, 'LIKE', $searchKey);

+0

我使用PostgreSQL。它有ILIKE(忽略LIKE)。 –

0

做到了。剛剛創建了新的匹配標記數組。另一個問題:誰知道如何將數組追加到分頁中的對象?

$matches = []; 
    foreach ($authors->items() as $author) { 
     $matches[$author->id]['name'] = 0; 
     foreach ($columns as $column) { 
      $matches[$author->id][$column] = 0; 
     } 

     foreach ($search as $searchKey) { 
      if (!empty($searchKey)) { 
       foreach ($author->toArray() as $key => $attribute) { 
        if (!strcasecmp($searchKey, $attribute)) { 
         $matches[$author->id][$key] = 1; 
        } 
       } 
      } 
     } 
    } 

    return response()->json([ 
     'data' => [ 
      'authors' => $authors, 
      'matches' => $matches 
     ], 
     'error' => null 
    ], 200);