【问题标题】:How to see matches of search in SQL?如何在 SQL 中查看搜索匹配项?
【发布时间】:2018-03-06 00:27:54
【问题描述】:

我有一个搜索行,用户在其中输入以逗号分隔的查询。我需要在 SQL 表中找到至少 1 个匹配项。但我也需要在每个找到的对象中标记匹配项。我该怎么做?

工作搜索(Laravel Eloquent (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);
}

对不起我的英语。

【问题讨论】:

  • 嘿,如果您正在研究高级搜索功能,您可能应该看看 Laravel Scout:laravel.com/docs/5.5/scout
  • @JulienBourdeau 嗨!我尝试了 Scout,但它对我不起作用(与 Algolia Driver 一起使用)。通过指令安装,搜索查询显示在 Algolia 网站上,但返回为空。不知道为什么。
  • 如果您愿意再试一次,请告诉我,我可以为您提供帮助。您可以在 discourse.algolia.com 上发帖(我正在监控 Laravel 问题)或在 SO 上发帖。

标签: php sql postgresql laravel eloquent


【解决方案1】:

做到了。刚刚为匹配标记创建了新数组。另一个问题:谁知道如何在分页中将数组附加到对象?

    $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);

【讨论】:

    【解决方案2】:

    在 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);

    【讨论】:

    • 我使用 PostgreSQL。它有 ILIKE(忽略 LIKE)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2017-09-12
    • 2021-11-16
    • 2014-07-10
    相关资源
    最近更新 更多