我有一个有 4 列的表格。我想根据输入显示行,并且它应该能够根据优先级字段优先显示。
示例:我的表格如下所示:
ID title description tags
1 web developer designer front-end
2 designer front-end web developer
3 front-end web developer designer
我的测试用例如下,它应该如何工作:
$input = 'web developer' // the sequence should be IDs : 1, 3, 2
$input = 'front-end' // output sequence result is : 3, 2, 1
$input = 'designer' // result sequence : 2, 1, 3
现在,我想根据输入对结果进行优先级排序,从标题到标签。
$blog = DB::('blogs')
->where('title', 'LIKE', '%$title%')
->where('description', 'LIKE', '%$title%')
->where('tags', 'LIKE', '%$title%');
但是上面的代码,好像没有..
最佳答案
我认为您想要对结果进行排序的逻辑应该出现在 ORDER BY
子句中。考虑以下原始查询:
SELECT *
FROM yourTable
ORDER BY
CASE WHEN title = 'web developer' THEN 0 ELSE 1 END,
CASE WHEN description = 'web developer' THEN 0 ELSE 1 END,
CASE WHEN tags = 'web developer' THEN 0 ELSE 1 END;
输出:
这是我使用 orderByRaw
尝试的 Laravel 代码:
$orderByClause = "CASE WHEN title = '".$input."' THEN 0 ELSE 1 END,";
$orderByClause .= "CASE WHEN description = '".$input."' THEN 0 ELSE 1 END,";
$orderByClause .= "CASE WHEN tags = '".$input."' THEN 0 ELSE 1 END";
$blog = DB::('blogs')
->orderByRaw($orderByClause)
->get();
我找不到任何有关如何参数化 orderByRaw
的(工作)文档,因此我使用了字符串连接。
此处演示:
Rextester
关于php - 如何在 Laravel Eloquent 中确定结果的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992637/