0
我正嘗試使用groupBy與Laravel的功能。這是我的查詢是否有可能在laravel雄辯中使用groupBy與「with」功能
$msgs=Conversation::where('sender', $sender)
->orWhere('reciever', $sender)
->orderBy('created_at', 'desc')
->with('message')
->get();
此查詢返回來自消息表的許多記錄,但我只想檢索一個。
這是數據,我想從組消息對象
{
"data": [
{
"id": 27,
"sender": 10,
"reciever": 4,
"created_at": "2017-07-26 22:46:04",
"updated_at": "2017-07-26 22:46:04",
"message": [
{
"id": 5,
"conversation_id": 27,
"last_sender": 10,
"msg": "5",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:46:04",
"updated_at": "2017-07-26 22:46:04"
},
{
"id": 6,
"conversation_id": 27,
"last_sender": 10,
"msg": "6",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:46:19",
"updated_at": "2017-07-26 22:46:19"
},
{
"id": 7,
"conversation_id": 27,
"last_sender": 10,
"msg": "7",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:46:35",
"updated_at": "2017-07-26 22:46:35"
},
{
"id": 8,
"conversation_id": 27,
"last_sender": 10,
"msg": "8",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:46:36",
"updated_at": "2017-07-26 22:46:36"
}
]
},
{
"id": 26,
"sender": 10,
"reciever": 7,
"created_at": "2017-07-26 22:40:02",
"updated_at": "2017-07-26 22:40:02",
"message": [
{
"id": 1,
"conversation_id": 26,
"last_sender": 10,
"msg": "1",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:40:02",
"updated_at": "2017-07-26 22:40:02"
},
{
"id": 2,
"conversation_id": 26,
"last_sender": 10,
"msg": "2",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:45:36",
"updated_at": "2017-07-26 22:45:36"
},
{
"id": 3,
"conversation_id": 26,
"last_sender": 10,
"msg": "3",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:45:50",
"updated_at": "2017-07-26 22:45:50"
},
{
"id": 4,
"conversation_id": 26,
"last_sender": 10,
"msg": "4",
"deleted": null,
"seen": null,
"created_at": "2017-07-26 22:45:57",
"updated_at": "2017-07-26 22:45:57"
}
]
}
]
}
任何幫助高度讚賞的結果。如果事情不清楚,請告訴我。謝謝。
謝謝你的幫助。但這不是我想要的。此查詢限制爲1,但我想對結果進行分組。你會更好地理解,如果你看到查詢「string(93)」select * from'conversations'其中'sender' =?或'reciever' =? order by'created_at' desc「 string(104)」select * from'messages' where'messages'.'conversation_id' in(?,?)order by'created_at' desc limit 1「 string(104)」select * from'messages' where'messages'.'conversation_id' in(?,?)order by'created_at' desc limit 1「」 – sadek
我猜我知道了,所以我說你可以在回調裏面應用任何東西,你可以做如下: ' - > with(['message'=> function($ query){0}}返回$ query-> whereIn('conversation_id',['value1','value2']) - > orderBy('created_at' ,'desc') - > first();' }]) – Sletheren
再次感謝。但沒有運氣。這是我用過的 「Conversation :: where('sender',$ sender) - > orWhere('reciever',$ sender) - > orderBy('created_at','desc') - > with([ 'message'=> function($ query){ $ query-> whereIn('conversation_id',['msg','seen']); }]) - > get();「 它不給任何消息對象的值.. 有一件事我注意到,我幾乎可以使用任何東西,但不能在回調中使用groupBy。 – sadek