这是我的聊天表
的表格结构 Schema::create('chats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->enum('block', ['no', 'yes'])->default('no');
$table->timestamps();
$table->bigInteger('user_one')->unsigned();
$table->foreign('user_one')
->references('id')
->on('users')
->onDelete('cascade');
$table->bigInteger('user_two')->unsigned();
$table->foreign('user_two')
->references('id')
->on('users')
->onDelete('cascade');
});
这是我的chat_messages表格的一个
Schema::create('chat_messages', function (Blueprint $table) {
$table->increments('id');
$table->enum('viewed', ['no', 'yes'])->default('no');
$table->string('msg', 1000);
$table->timestamps();
$table->bigInteger('chat_id')->unsigned();
$table->foreign('chat_id')
->references('id')
->on('chats')
->onDelete('cascade');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
我现在的问题是我想运行这个在phpmyadmin中工作正常的查询
SELECT U.id,C.id,U.name,U.email FROM users as U, chats as C, chat_messages as M WHERE CASE WHEN C.user_one = '2' THEN C.user_two = U.id WHEN C.user_two = '2' THEN C.user_one= U.id END AND C.id = M.chat_id AND (C.user_one ='2' OR C.user_two ='2') ORDER BY C.id DESC
以下是使用Laravel查询构建器的上述查询的版本,似乎无法正常工作
$authUser = Auth::user()->id;
$chatList = DB::select(DB::raw('U.id, C.id, U.name'))
->from(DB::raw('users as U, chats as C, chat_messages as M'))
->where(DB::raw('CASE
WHEN C.user_one = '.Auth::user()->id.'
THEN C.user_two = U.id
WHEN C.user_two = '.Auth::user()->id.'
THEN C.user_one= U.id END'))
->where('C.id', '=', 'M.chat_id')
->where(function($query) use ($authUser) {
$query->where('C.user_one', '=', $authUser)
->orWhere('C.user_two', '=', $authUser);
})
->orderBy('C.id', 'desc')
->get();
它出了这个错误
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'U.id, C.id, U.name' at line 1 (SQL: U.id, C.id, U.name)
我已经尝试了很多方法,但似乎没有用......我需要你的帮助才能弄清楚如何解决这个问题...谢谢
答案 0 :(得分:0)
这里是
$authUser = Auth::user()->id;
$chatList = DB::table(DB::raw('users as U, chats as C, chat_messages as M'))
->select(DB::raw('U.id, C.id, U.name, U.email'))
->whereRaw('CASE
WHEN C.user_one = '.Auth::user()->id.'
THEN C.user_two = U.id
WHEN C.user_two = '.Auth::user()->id.'
THEN C.user_one= U.id END
AND C.id = M.chat_id AND
(C.user_one = '.$authUser.' OR C.user_two = '.$authUser.')')
->orderBy('C.id', 'DESC')
->get();