From f406d7568036cbcef2f5945c465eb16d2a5d856c Mon Sep 17 00:00:00 2001 From: Kevin Wheeler Date: Sat, 19 Nov 2022 09:20:36 -0600 Subject: [PATCH] Fixed support for HasOne relationships when sorting --- src/PrimevueDatatables.php | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/PrimevueDatatables.php b/src/PrimevueDatatables.php index 6e81b45..a0b8213 100644 --- a/src/PrimevueDatatables.php +++ b/src/PrimevueDatatables.php @@ -49,6 +49,7 @@ public function query(Builder $query): static { } public static function of(Builder $query): static { + // I'm pretty sure passing $query as an argument doesn't actually do anything. $instance = new self($query); return $instance->query($query); } @@ -125,21 +126,20 @@ private function applySort(Builder &$q) } elseif (sizeof($key) === 2) { $relationship = $this->getRelatedFromMethodName($key[0], get_class($q->getModel())); if ($relationship) { - $ownerKey = $relationship->getOwnerKeyName(); - $fKey = $relationship->getForeignKeyName(); - $fTable = $relationship->getRelated()->getTable(); - $ownerTable = $relationship->getParent()->getTable(); - if ($relationship instanceof BelongsTo) { - $q->orderBy( - get_class($relationship->getRelated())::query()->select($key[1])->whereColumn("$fTable.$ownerKey", "$ownerTable.$fKey"), - $this->sortDirection ?? 'asc' - ); - } elseif ($relationship instanceof HasOne) { - $q->orderBy( - get_class($relationship->getRelated())::select($key[1])->whereColumn("$fTable.$fKey", "$ownerTable.$ownerKey"), - $this->sortDirection ?? 'asc' - ); + $parentTable = $relationship->getParent()->getTable(); + $relatedTable = $relationship->getRelated()->getTable(); + if ($relationship instanceof HasOne) { + $parentKey = explode(".", $relationship->getQualifiedParentKeyName())[1]; + $relatedKey = $relationship->getForeignKeyName(); + } else { + $parentKey = $relationship->getForeignKeyName(); + $relatedKey = $relationship->getOwnerKeyName(); } + + $q->orderBy( + get_class($relationship->getRelated())::query()->select($key[1])->whereColumn("$parentTable.$parentKey", "$relatedTable.$relatedKey"), + $this->sortDirection ?? 'asc' + ); /*$q->join($fTable, "$ownerTable.$fKey", '=', "$fTable.$ownerKey") ->orderBy($fTable.".".$key[1],$this->sortDirection ?? 'asc');*/ /*$q->orderBy($fKey,$this->sortDirection ?? 'asc');*/