Skip to content

Commit 5c2808d

Browse files
committed
add ability to getWhere and getWhereFirst By sorted condition
1 parent d286f41 commit 5c2808d

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/Repository/Concerns/SelectsEntity.php

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ public function existed($column, $value = null)
195195
}
196196

197197
/**
198-
* Finds models with "where" condition and sort. Default sorted by desc primary key
198+
* Finds models with "where" condition by order. Default sorted by desc primary key
199199
*
200200
* @param array $conditions
201201
* @param array|null $sortedBy
@@ -204,16 +204,37 @@ public function existed($column, $value = null)
204204
*
205205
* @return Builder[]|Collection
206206
*/
207-
public function getWhereAndSort(array $conditions, array $sortedBy = null, ?int $limit = 5000, ?int $offset = 0)
207+
public function getWhereWithSorted(array $conditions, array $sortedBy = null, ?int $limit = 5000, ?int $offset = 0)
208+
{
209+
$delegator = $this->getDelegatorByConditionsAndSortedBy($conditions, $sortedBy);
210+
return $delegator->skip($offset)->take($limit)->get();
211+
}
212+
213+
private function getDelegatorByConditionsAndSortedBy(array $conditions, array $sortedBy = null)
208214
{
209215
$sortedBy = empty($sortedBy) ? [$this->model->getKeyName() => 'desc'] : $sortedBy;
210-
$delegator = $this->model;
211-
foreach ($conditions as $key => $val) {
212-
$delegator = $delegator->where($key, $val);
213-
}
216+
$delegator = $this->model->where($conditions);
214217
foreach ($sortedBy as $key => $val) {
215218
$delegator = $delegator->orderBy($key, $val);
216219
}
217-
return $delegator->skip($offset)->take($limit)->get();
220+
return $delegator;
221+
}
222+
223+
/**
224+
* Get a model with "where" condition by order. Default sorted by desc primary key
225+
*
226+
* @param array $conditions
227+
* @param array|null $sortedBy
228+
*
229+
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
230+
*/
231+
public function getWhereFirstWithSorted(array $conditions, array $sortedBy = null)
232+
{
233+
$delegator = $this->getDelegatorByConditionsAndSortedBy($conditions, $sortedBy);
234+
$model = $delegator->take(1)->first();
235+
if (!$model) {
236+
$this->throwModelNotFoundException();
237+
}
238+
return $model;
218239
}
219240
}

0 commit comments

Comments
 (0)