Skip to content

Commit 2a542b4

Browse files
committed
support PK and FK on views based on naming convention
1 parent 4f2a8ec commit 2a542b4

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

src/Tqdev/PhpCrudApi/Column/Reflection/ReflectedTable.php

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,23 +49,43 @@ public static function fromReflection(GenericReflection $reflection, string $nam
4949
$columns[$column->getName()] = $column;
5050
}
5151
// set primary key
52-
$columnNames = $reflection->getTablePrimaryKeys($name);
53-
if (count($columnNames) == 1) {
54-
$columnName = $columnNames[0];
55-
if (isset($columns[$columnName])) {
56-
$pk = $columns[$columnName];
57-
$pk->setPk(true);
52+
$columnName = false;
53+
if ($type == 'view') {
54+
$columnName = 'id';
55+
} else {
56+
$columnNames = $reflection->getTablePrimaryKeys($name);
57+
if (count($columnNames) == 1) {
58+
$columnName = $columnNames[0];
5859
}
5960
}
61+
if ($columnName && isset($columns[$columnName])) {
62+
$pk = $columns[$columnName];
63+
$pk->setPk(true);
64+
}
6065
// set foreign keys
61-
$fks = $reflection->getTableForeignKeys($name);
62-
foreach ($fks as $columnName => $table) {
63-
$columns[$columnName]->setFk($table);
66+
if ($type == 'view') {
67+
$tables = $reflection->getTables();
68+
foreach ($columns as $columnName => $column) {
69+
if (substr($columnName, -3) == '_id') {
70+
foreach ($tables as $table) {
71+
$tableName = $table['TABLE_NAME'];
72+
$suffix = $tableName . '_id';
73+
if (substr($columnName, -1 * strlen($suffix)) == $suffix) {
74+
$column->setFk($tableName);
75+
}
76+
}
77+
}
78+
}
79+
} else {
80+
$fks = $reflection->getTableForeignKeys($name);
81+
foreach ($fks as $columnName => $table) {
82+
$columns[$columnName]->setFk($table);
83+
}
6484
}
6585
return new ReflectedTable($name, $type, array_values($columns));
6686
}
6787

68-
public static function fromJson(/* object */$json): ReflectedTable
88+
public static function fromJson( /* object */$json): ReflectedTable
6989
{
7090
$name = $json->name;
7191
$type = isset($json->type) ? $json->type : 'table';

0 commit comments

Comments
 (0)