Laravel使用案例声明

时间:2018-11-20 21:24:59

标签: sql laravel

我正在尝试检索对话的所有消息并显示其状态(已读或未读)。我使用CASE尝试读取message.read属性(布尔值)并将其处理为字符串。

$messages = DB::table('conversation_message')
->select(
    'messages.id as message_id',
    'messages.created_at as send_at',
    'messages.user_id as from_id',
    'messages.body as body',
    'conversations.id as conversation',
    DB::raw('(CASE WHEN messages.read = 1 THEN read ELSE unread END) AS status')
)
->leftjoin('messages', 'messages.id', '=', 'conversation_message.message_id')
->leftjoin('conversations', 'conversations.id', '=', 'conversation_message.conversation_id')
->orderBy('send_at', 'asc')
->get();

在没有CASE的情况下,查询工作正常,但是在我收到Syntax error or access violation: 1064附近的'read的情况下。

1 个答案:

答案 0 :(得分:0)

通过将结果readunread放在双引号中解决了该问题。

$messages = DB::table('conversation_message')
->select(
    'messages.id as message_id',
    'messages.created_at as send_at',
    'messages.user_id as from_id',
    'messages.body as body',
    'conversations.id as conversation',
    DB::raw('(CASE WHEN messages.read = 1 THEN "read" ELSE "unread" END) AS status')
)
->leftjoin('messages', 'messages.id', '=', 'conversation_message.message_id')
->leftjoin('conversations', 'conversations.id', '=', 'conversation_message.conversation_id')
->orderBy('send_at', 'asc')
->get();

现在我可以将status直接用作CSS类!