Skip to content

Commit 363d63b

Browse files
author
Roman Dubrovin
committed
Merge branch 'dpankratov/refact-ordering-functions' into 'master'
refact scopeOrderByRelated method See merge request components/laravel-helpers!39
2 parents a820bac + ed852e6 commit 363d63b

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/Traits/ModelTrait.php

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ public function scopeAddFieldsToSelect($query, $fields)
5252
return $query;
5353
}
5454

55-
public function withCount($query, $target, $as = 'count') {
55+
public function withCount($query, $target, $as = 'count')
56+
{
5657
$targetTable = (new $target)->getTable();
5758
$fields = $this->getAllFieldsWithTable();
5859
$currentTable = $this->getTable();
@@ -69,20 +70,24 @@ public function withCount($query, $target, $as = 'count') {
6970
->groupBy($fields);
7071
}
7172

72-
public function scopeOrderByRelated($query, $targetModel, $field, $desc = 'DESC') {
73-
$targetTable = (new $targetModel)->getTable();
74-
$fields = $this->getAllFieldsWithTable();
75-
$currentTable = $this->getTable();
76-
$relationFieldName = Str::singular($currentTable) . '_id';
73+
public function scopeOrderByRelated($query, $orderField, $desc = 'DESC')
74+
{
75+
$entities = explode('.', $orderField);
7776

78-
if (empty($this->selectedFields)) {
79-
$this->selectedFields = $fields;
80-
$fields[] = "{$targetTable}.{$field}";
77+
$fieldName = array_pop($entities);
78+
$relationName = array_shift($entities);
8179

82-
$query->select($fields);
83-
}
80+
if (Str::plural($relationName) !== $relationName) {
81+
$table = $this->getTable();
82+
$relation = $this->__callStatic($relationName, []);
8483

85-
$query->join($targetTable, "{$targetTable}.{$relationFieldName}", '=', "{$currentTable}.id")
86-
->orderBy($field, $desc);
84+
$relatedTable = $relation->getRelated()->getTable();
85+
$foreignKey = $relation->getForeignKey();
86+
$ownerKey = $relation->getOwnerKey();
87+
88+
$query
89+
->addSelect("{$table}.*", DB::raw("(SELECT {$fieldName} FROM {$relatedTable} WHERE {$foreignKey} = {$relatedTable}.{$ownerKey} ) as orderedField"))
90+
->orderBy('orderedField', $desc);
91+
}
8792
}
8893
}

0 commit comments

Comments
 (0)