简体   繁体   English

如何在 Laravel 数据库查询生成器中使用 CASE WHEN IN

[英]How to use CASE WHEN IN in Laravel database query builder

I have users table and a followers table.我有users表和followers表。 I'm doing a search to get all the users with a specific keyword, but I want the ones which are followers of the current user to appear first.我正在搜索以获取具有特定关键字的所有用户,但我希望作为当前用户关注者的用户首先出现。 I can get all the followers id's in a subquery, so my idea was to do something like this:我可以在子查询中获取所有关注者 ID,所以我的想法是做这样的事情:

SELECT id, name, surname, 
CASE WHEN id IN (SELECT followable_id FROM followers WHERE followable_id = $currentUserId --this is a variable)  THEN 1
ELSE 0
END AS friend
FROM users
ORDER BY friend
WHERE name = 'keyword';

I've been trying to get this in my Laravel controller, but I can't find the way.我一直试图在我的 Laravel controller 中得到这个,但我找不到方法。 How could I use this SQL select in my Laravel controller?我怎么能在我的 Laravel Z594C103F2C6E10C3D8AB059F01 How could translate this SQL code to the Laravel Database Query Builder ?如何将此 SQL 代码转换为Laravel 数据库查询生成器

What I have already tried:我已经尝试过的:

Following @aynber answer, I wrote the following code:在@aynber 回答之后,我编写了以下代码:

$orderedMachingUsers = DB::table('users')
    ->whereIn('id', $matchingUsersId)->select(
        [
            '*', 
            DB::raw('CASE WHEN id IN ? THEN 1 ELSE 0 END AS friend', [$friendsId])]
    )
    ->orderByRaw('friend')
    ->get();

It seems close, but I'm still geting a "SQLSTATE[42000]: Syntax error or access violation: 1064" error.看起来很接近,但我仍然收到“SQLSTATE [42000]:语法错误或访问冲突:1064”错误。

You need to pass the case statement in with a raw clause您需要使用原始子句传递 case 语句

DB::table('users')
    ->where('name', 'keyword')->select(
        [
            'id', 
            'name', 
            'surname', 
            DB::raw('CASE WHEN id IN (SELECT followable_id FROM followers WHERE followable_id = ?) THEN 1 ELSE 0 END AS friend', [$curentUserId])]
    )
    ->orderByRaw('friend')
    ->get();

the syntax for in condition should be like CASE WHEN id IN (?,?,?) THEN so you need to add ? in条件的语法应该类似于CASE WHEN id IN (?,?,?) THEN所以你需要添加? with the count of $friendsId$friendsId的计数

so you should use the following所以你应该使用以下

$placeholders = str_repeat ('?,',  count($friendsId) - 1) . '?';
$orderedMachingUsers = DB::table('users')
    ->whereIn('id', $matchingUsersId)->select(
        [
            '*', 
            DB::raw('CASE WHEN id IN ('. $placeholders .') THEN 1 ELSE 0 END AS friend', [$friendsId])]
    )
    ->orderByRaw('friend')
    ->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM