From ec4b04b40e763969911f98764a1bbfb39e96f196 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Sat, 15 Jan 2022 13:31:10 +0100 Subject: [PATCH] app/Http/Livewire/Traits/WithSort.php: sort relationships using PowerJoins --- app/Http/Livewire/Traits/WithSort.php | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/Http/Livewire/Traits/WithSort.php b/app/Http/Livewire/Traits/WithSort.php index f795fec..2303ed7 100644 --- a/app/Http/Livewire/Traits/WithSort.php +++ b/app/Http/Livewire/Traits/WithSort.php @@ -47,7 +47,23 @@ trait WithSort { } foreach($columns as $column) { - $query->orderBy($this->orderExpr($column), $this->dir); + + // If column is a relationship + $p = strrpos($column, '.'); + if ($p !== false) { + $rel = substr($column, 0, $p); + $col = substr($column, $p + 1); + try { + $query->orderByLeftPowerJoins([$rel, $this->orderExpr($col)], $this->dir); + } catch(\BadMethodCallException $e) { + $class = get_class($query->getModel()); + throw new \Error("Failed to sort column '$column': '$class' " + . "must use 'Kirschbaum\PowerJoins\PowerJoins' " + . "trait to be able to sort by relationship."); + } + } else { + $query->orderBy($this->orderExpr($column), $this->dir); + } } }