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

dani94's avatar

OrderBy third relationship

Hey guys, I have 3 tables.

Reports. Orders. Events. Workers

1 Report has 1 Order. 1 Order has 1 Event. 1 Worker has many Reports

My Report Model

    public function event()
    {
        return $this->belongsTo('App\Event')->latest('date')->withDefault();
    }

My Order Model

    public function event()
    {
        return $this->belongsTo('App\Event')->withDefault();
    }

My Event Model

    public function order()
    {
        return $this->hasOne('App\Order')->withDefault();
    }

My Worker Model

    public function event()
    {
        return $this->belongsTo('App\Event')->latest('date')->withDefault();
    }

Well, I need to get all reports by a worker order by event.date.

        $reports = $worker->reports()
            ->with(['event:id,name,date'])
            ->simplePaginate(20);

The problem is that reports are not ordering... I dont know why.

Its executing 2 querys:


select `reports`.*, `report_worker`.`worker_id` as `pivot_worker_id`, `report_worker`.`report_id` as `pivot_report_id` from `reports` inner join `report_worker` on `reports`.`id` = `report_worker`.`report_id` where `report_worker`.`worker_id` = 3 limit 21 offset 0


select `id`, `name`, `date` from `events` where `events`.`id` in (2, 3, 5, 8, 65, 69, 107, 136, 137, 163, 166, 171, 185) order by `date` desc

Can you help me please?

0 likes
1 reply
bobbybouwmann's avatar

This is because Laravel doesn't create joins to fetch the relationship data here. So, in this case, the ordering only applies to the separated query. After that Laravel will match the results of the 2 queries into the correct models and finally in a collection.

If you want to order everything by event you need to use a join instead.

Please or to participate in this conversation.