如何在SQL中查看搜索匹配?

时间:2017-09-25 05:48:34

标签: php sql postgresql laravel eloquent

我有一条搜索行,用户输入查询除以逗号。我需要在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);
}

抱歉我的英文。

2 个答案:

答案 0 :(得分:0)

在laravel或Mysql中没有像LIKE这样的条件。应该有ILIKE。有两行代码$query->orWhere('name', 'ILIKE', '%'.$searchKey.'%');

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

I

从以上两行的ILIKE中删除I。从ILIKE移除$query->orWhere('name', 'LIKE', '%'.$searchKey.'%');后,它应该看起来像

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

node ./node_modules/serverless/bin/serverless remove

答案 1 :(得分: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);