Created
December 25, 2019 21:37
-
-
Save mtvbrianking/402ef6c68fc76131e4be5a2b2f59a979 to your computer and use it in GitHub Desktop.
Translate model to table fields
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 | |
$tableModelMap = [ | |
'orders' => null, | |
'customers' => 'customer', | |
]; | |
$modelFields = [ | |
'id', | |
'customer.id', | |
'customer.name', | |
'is_paid', | |
'sub_total', | |
'tax_rate', | |
'total', | |
'deleted_at', | |
]; | |
$modelTableColumns = [ | |
'id' => 'orders.id', | |
'customer.id' => 'customers.id', | |
'customer.name' => 'customers.name', | |
'is_paid' => 'orders.is_paid', | |
'sub_total' => 'orders.sub_total', | |
'tax_rate' => 'orders.tax_rate', | |
'total' => 'orders.total', | |
'deleted_at' => 'orders.deleted_at', | |
]; | |
function getTableField(string $modelField, array $tableModelMap): string | |
{ | |
if(empty($tableModelMap)) { | |
return $modelField; | |
} | |
$model = null; | |
$field = $modelField; | |
$modelFieldParts = explode('.', $modelField); | |
if(count($modelFieldParts) > 1) { | |
$model = $modelFieldParts[0]; | |
$field = $modelFieldParts[1]; | |
} | |
$table = array_search($model, $tableModelMap); | |
$tableField = "{$table}.{$field}"; | |
return $tableField; | |
} | |
echo json_encode(getTableField('id', $tableModelMap)); | |
function modelToTableFields(array $fields, array $tableModelMap, bool $prefixCols = false): array | |
{ | |
if(empty($tableModelMap)) { | |
return $fields; | |
} | |
foreach($fields as &$field) | |
{ | |
$model = null; | |
$modelField = explode('.', $field); | |
if(count($modelField) > 1) { | |
$model = $modelField[0]; | |
$field = $modelField[1]; | |
} | |
$table = array_search($model, $tableModelMap); | |
$tableField = "{$table}.{$field}"; | |
$field = $prefixCols ? "{$tableField} AS {$tableField}" : $tableField; | |
} | |
return $fields; | |
} | |
// echo json_encode(modelToTableFields($modelFields, $tableModelMap, false)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment