Skip to content

Commit

Permalink
Merge pull request #12 from kevinwheeler/kevinwheeler-hasOne-sorting
Browse files Browse the repository at this point in the history
Fixed support for HasOne relationships when sorting
  • Loading branch information
coolsam726 authored Dec 30, 2022
2 parents 4c02d3d + f406d75 commit b7588cc
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/PrimevueDatatables.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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');*/
Expand Down

0 comments on commit b7588cc

Please sign in to comment.