I am trying to get the last message from each conversation, the only problem is I am not using a conversations table.
I am using one messages table, my table columns looks like this:
id from_id to_id text isread isseen created_at updated_at
Right now I am able to retrieve conversations like this:
$messages = Message::select('*')-> from(DB::raw("(select * from `messages` where `to_id` = ".Auth::id()." order by `created_at` desc) as sub"))-> groupBy('from_id')->orderBy('created_at', 'desc')-> paginate(7);
The only downside to this is I am not retrieving the last message for each conversation, I am retrieving the last message received.
How can I retrieve the last message of each conversation?
Example Retrieve user63 conversations and last message for each conversation:
id from_id to_id text isread isseen created_at updated_at 23 224 63 a 0 0 2015-03-28 22:23:54 2015-03-28 22:23:54 20 63 225 b 0 0 2015-03-28 22:23:06 2015-03-28 22:23:06 16 225 63 hi 0 1 2015-03-28 22:21:32 2015-03-28 22:21:32
I thought of an idea, not sure though:
$messages = Message::select('*')-> from(DB::raw(" ( (select *, to_id as theuser from `messages` where `to_id` = ".Auth::id()." order by `created_at` desc) union (select *, from_id as theuser from `messages` where `from_id` = ".Auth::id()." order by `created_at` desc) group by theuser ) as sub"))-> groupBy('from_id')->orderBy('created_at', 'desc')-> paginate(7);