Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dani94's avatar

Order a query by date from two different tables

Hey guys!

I would like to order my query by field date from two different tables. I have a Model Report with date. One report has (or not) one event with date. If a report has an event, the report date is null. So it only exists one date, or from report or from event. Our structure is something like this:

Report:
{
// no date, but event with date
"event": {
	"date": "08-06-2021"
	}
}

Another Report:
{
// date but not event
"date": "07-06-2021"
}

I tried something like this, but didnt work. Any ideas?

        return $this->reports()
            ->with(['event' => function ($query) {
                $query->orderBy('date', 'desc');
            }])
            ->orderBy('date', 'desc');
0 likes
4 replies
SilenceBringer's avatar

@dani94

return $this->reports()
    ->select('reports.*', 'events.*', DB::raw('if(events.date, events.date, reports.date) as order_date'))
    ->join('events', 'events.report_id', '=', 'reports.id') // put your join conditions here
    ->orderBy('order_date', 'desc');
1 like
dani94's avatar

This doesnt fetch the reports without events

Please or to participate in this conversation.