[英]Merge two mysql rows into one using laravel
我有一個名為messages的表,其結構如下:
id | sender_id | receiver_id | message | sent_at
我已經建立了一個系統,每當用戶選擇一個特定的用戶時,該頁面上就會以適當的方式顯示由他發送或接收的消息。 為此,我有以下代碼可以完成該任務:
<script type="text/javascript">
function showMessages(elem){
let id = $(elem).attr('id');
let myId = "<?php echo \Session::get('user_id'); ?>";
console.log(id, myId);
$.get("/get-messages",
{
id_no_1: id,
id_no_2: myId
}, function(data){
alert(data)
});
}
在這里,我獲得了關聯用戶和我自己的用戶的user_id,並對路由執行AJAX請求,並且該路由具有:
Route::get('/get-messages', 'PagesController@getMessages');
我的主要功能如下所示:
public function getMessages(){
$id_no_1 = request('id_no_1');
$id_no_2 = request('id_no_2');
$messagesSendByOneToTwo = DB::table('messages')
->where('sender_id', $id_no_1)
->where('receiver_id', $id_no_2)
->get();
// $messagesSendByOneToTwo = json_encode($messagesSendByOneToTwo);
$messagesSendByTwoToOne = DB::table('messages')
->where('sender_id', $id_no_2)
->where('receiver_id', $id_no_1)
->get();
// $messagesSendByOneToTwo = json_encode($messagesSendByTwoToOne);
$allMessages = array_merge($messagesSendByOneToTwo, $messagesSendByTwoToOne);
$allMessages = json_encode($allMessages);
echo $allMessages;
}
那里有兩個變量,我想將兩個變量合並為一個變量。 我嘗試了array_merge();
我知道這是行不通的,因為變量不是數組。 對於這個問題,我有以下可能的解決方案:
您沒有理由先做兩個查詢:
public function getMessages(){
$id_no_1 = request('id_no_1');
$id_no_2 = request('id_no_2');
$messagesSent = DB::table('messages')
->whereIn('sender_id', [ $id_no_1, $id_no_2 ])
->whereIn('receiver_id', [ $id_no_1, $id_no_2 ])
->get();
return response()->json($messagesSent); //This is better than echoing json
}
如果需要數組,可以嘗試以下代碼獲取數組而不是集合。
messagesSendByOneToTwo = DB::table('messages')
->where('sender_id', $id_no_1)
->where('receiver_id', $id_no_2)
->get()->toArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.