2
我正在尝试使用搜索表单来查找用户。按公式计算的SQL重量行
我如何根据以下公式计算行数?
score = isInTheSameCityWithMe + isInTheSameStateWithMe + isInTheSameCountryWithMe
因此,如果我住在巴黎,它应该把居住在巴黎的人放在顶端。
我的实现是这样
<code>$users = \DB::table('users')->
select('name', 'id', 'city', 'country', 'avatar');
if(\Auth::user()->hasLocation()) {
$weightString = '';
if(\Auth::user()->hasLocationFullToCity())
$weightString = 'CASE WHEN users.city = \''.\Auth::user()->city.'\' THEN 4 ELSE
CASE WHEN users.state = \''.\Auth::user()->state.'\' THEN 3 ELSE
CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END END';
elseif(\Auth::user()->hasLocationFullToState())
$weightString = 'CASE WHEN users.state = \''.\Auth::user()->state.'\' THEN 3 ELSE
CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END';
elseif(\Auth::user()->country)
$weightString = 'CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END';
$users->addSelect(\DB::raw($weightString.' AS score'))->orderBy('score', 'DESC');
}
这给我像
select `name`, `id`, `city`, `country`, `avatar`, CASE WHEN users.city = 'Cluj Napoca' THEN 4 ELSE CASE WHEN users.state = 'Cluj' THEN 3 ELSE CASE WHEN users.country = 'Romainia' THEN 2 ELSE 1 END END END AS score from `users` where `name` LIKE ? order by `score` desc
查询是否有更好的办法?