Last active
August 12, 2020 22:37
-
-
Save kamaroly/4d8e4cd25685871812c9457ca681eb2a to your computer and use it in GitHub Desktop.
These two methods are helpers to be added in eloquent when you want to only extract raw query conditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model as EloquentModel; | |
class Model extends EloquentModel | |
{ | |
/** | |
* Get Underlying query conditions | |
* @param $query eloquent query builder | |
* @param array $withoutTheseColumns | |
* @param array $withOnlyTheseColumns | |
* @return string | |
*/ | |
public function scopeGetSqlConditions($query, $withoutTheseColumns = [], $withOnlyTheseColumns = []) | |
{ | |
$conditions = collect($query->getQuery()->wheres); | |
// Remove Columns that are not desired | |
$conditions->reject(function ($condition) use($withoutTheseColumns) { | |
return isset($condition['column']) ? in_array($condition['column'], $withoutTheseColumns) : false; | |
}); | |
// Consider only these columns | |
$conditions->reject(function ($condition) use($withOnlyTheseColumns) { | |
return isset($condition['column']) ? !in_array($condition['column'], $withOnlyTheseColumns) : true; | |
}); | |
// Build query with conditions | |
return $conditions->transform(function($item, $key){ | |
// If this is the first condition, then don't prefix with the | |
// boolean, just skipp it | |
if ($key == 0) { | |
$item['boolean'] = ''; | |
} | |
// If this is a raw sql query, then don't concatenate, use exactly | |
// what the user has provide, othewise build the conditional | |
// query | |
if (isset($item['sql'])) { | |
return "{$item['boolean']} {$item['sql']}"; | |
} | |
// For us to reach here, the user didn't provide raw Sql. | |
return "{$item['boolean']} {$item['column']} {$item['operator']} '{$item['value']}'"; | |
})->implode(" "); | |
} | |
/** | |
* Get Condition values for specific columns | |
* @param QueryBuild $query | |
* @param array $columnsToGetValueFor | |
* @return array | collection | |
*/ | |
public function scopeConditionValues($query, array $columnsToGetValueFor = []) | |
{ | |
return collect($query->getQuery()->wheres) | |
->whereIn('column', $columnsToGetValueFor) | |
->transform(function($item){ | |
return [$item['column'] => $item['value']]; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment