Skip to content

Commit

Permalink
optimized findBy function
Browse files Browse the repository at this point in the history
  • Loading branch information
DevDynamo2024 committed Aug 29, 2019
1 parent 2a3ad68 commit 3fb97f4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
6 changes: 4 additions & 2 deletions src/Uniqueway/Repositories/Contracts/RepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ public function find($id, $columns = ['*']);

/**
* @param $attribute
* @param $value
* @param string $value
* @param array $columns
* @param bool $or
* @return mixed
* @author Taylor <[email protected]>
*/
public function findBy($attribute, $value = '', $columns = ['*']);
public function findBy($attribute, $value = '', $columns = ['*'], $or = false);

/**
* @param $field
Expand Down
40 changes: 37 additions & 3 deletions src/Uniqueway/Repositories/Eloquent/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,49 @@ public function find($id, $columns = ['*'])
* @param array $columns
* @return mixed
*/
public function findBy($attribute, $value = '', $columns = ['*'])
/**
* @param $attribute
* @param string $value
* @param array $columns
* @param bool $or
* @return mixed
* @author Taylor <[email protected]>
*/
public function findBy($attribute, $value = '', $columns = ['*'], $or = false)
{
$this->applyCriteria();

$model = $this->model;

if (is_array($attribute)) {
return $this->model->where($attribute)->first($columns);
foreach ($attribute as $field => $value) {
if ($value instanceof \Closure) {
$model = (!$or)
? $model->where($value)
: $model->orWhere($value);
} elseif (is_array($value)) {
if (count($value) === 3) {
list($field, $operator, $search) = $value;
$model = (!$or)
? $model->where($field, $operator, $search)
: $model->orWhere($field, $operator, $search);
} elseif (count($value) === 2) {
list($field, $search) = $value;
$model = (!$or)
? $model->where($field, '=', $search)
: $model->orWhere($field, '=', $search);
}
} else {
$model = (!$or)
? $model->where($field, '=', $value)
: $model->orWhere($field, '=', $value);
}
}

return $model->first($columns);
}

return $this->model->where($attribute, '=', $value)->first($columns);
return $model->where($attribute, '=', $value)->first($columns);
}

/**
Expand Down

0 comments on commit 3fb97f4

Please sign in to comment.