F
F
Fear12018-10-19 13:21:59
Laravel
Fear1, 2018-10-19 13:21:59

How to sort by adjacent Laravel table?

Have a request

Card::leftJoin('comments', 'cards.id', '=', 'comments.card_id')
            ->select('cards.id')
            ->orderBy('comments.created_at', 'desc')
            ->groupBy('id')
            ->get();

Joinite, sorts by comment creation date and groups by card_id. But it groups incorrectly. I don’t understand where the error is ...
Query result:
5bc9af8e1f4bb968367913.png
Sorting in the database by creation date:
5bc9afa2f2e81644387549.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fear1, 2018-10-19
@Fear1

It turned out to be done through the filter as follows:

Card::leftJoin('comments', 'cards.id', '=', 'comments.card_id')
        ->where('comments.type', 'comment')
        ->select('cards.*')
        ->orderBy('comments.created_at', 'desc')
        ->groupBy('comments.id')
        ->get()
        ->filter(function($item, $key) {
            if(!in_array($item->id, $this->alreadySelectedCards)) {
                $this->alreadySelectedCards[] = $item->id;
                return true;
            }
        });

But this is a crutch and, it seems to me, there is a normal way to solve such a trivial problem...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question