mercredi 13 janvier 2016

Group and sort results by max and count in joined table using QueryBuilder

I'm making an app for selling books but I'm struggling with this part of it.

When a user wants to buy a book he can send a message to the book's seller. I have a table called conversations and another table called messages, which holds the messages for a conversation.

I have a page where a user can see a list of conversations he's involved. Conversations with the latest messages should be shown first. I solved this already but I also want to show the number of unread messages next to each conversation (messages have a "read" boolean field). I haven't been able to add the count as part of my original query; I know I could make a query for each item in the conversations collection but that would be inefficient as hell.

This is my query so far with the QueryBuilder:

$conversations = DB::table('conversations')
            ->select([
                'books.title as bookTitle', 'conversations.id',
                 DB::raw('max(messages.created_at) as lastMessage'),
                // DB::raw('(select count(id) from messages')
            ])
            ->where('conversations.from_user', $this->user->id)
            ->orWhere('conversations.to_user', $this->user->id)
            ->join('books', 'conversations.book_id', '=', 'books.id')
            ->join('messages', 'conversations.id', '=', 'messages.conversation_id')
            ->groupBy('messages.conversation_id')
            ->orderBy('lastMessage', 'DESC')
            ->get();

If i add the part commented out to attempt to get a field with the number of unread messages for that conversation I get a SQL syntax error. I also been thinking if maybe is not possible to add the count field since it might be exclusive to my original query: I sort the conversations taking into account all messages (read or unread) and pick the latest message for each conversation; the count field I want to add should only count unread messages.

Any ideas? Hope I explained myself.

Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire