/** * Get the field names for a given table. * * @param Table $table The table * * @return string[] An array of field names */ public function relationshipsForTable(Table $table) { $database = $this->instance->databaseName; $relationships = []; // Fetch all the to-one relationships $result = $this->client->query("SELECT `constraint_name`, `column_name`, `referenced_table_name`, `referenced_column_name` FROM `information_schema`.`key_column_usage` WHERE `referenced_table_name` IS NOT NULL AND `table_schema`='{$database}' AND `table_name`='{$table->name}'"); if ($result !== false) { // Loop through the relationships, and add each one to the array while ($data = $result->fetch(PDO::FETCH_ASSOC)) { $relationships[Str::singularize($data['referenced_table_name'])] = (object) ['column' => $data['column_name'], 'table' => $data['referenced_table_name'], 'references' => $data['referenced_column_name']]; } } // Fetch all the to-many relationships $result = $this->client->query("SELECT `constraint_name`, `column_name`, `table_name`, `referenced_column_name` FROM `information_schema`.`key_column_usage` WHERE `table_name` IS NOT NULL AND `table_schema`='{$database}' AND `referenced_table_name`='{$table->name}'"); // If no results are returned, return an empty array if ($result !== false) { // Loop through the relationships, and add each one to the array while ($data = $result->fetch(PDO::FETCH_ASSOC)) { $relationships[Str::pluralize($data['table_name'])] = (object) ['column' => $data['referenced_column_name'], 'table' => $data['table_name'], 'references' => $data['column_name']]; } } return $relationships; }
/** * Work the model class based on the table name, and cache it for later. * * @param Table $table The table to get a model for * * @return string The name of a model class */ protected function getModelClass($table) { if (isset(static::$modelClassCache[$table->name])) { return static::$modelClassCache[$table->name]; } $namespace = null; $config = Config::get($table->instance->name); if (isset($config->model_namespace)) { $namespace = $config->model_namespace; } if ($namespace === null) { $config = Config::get('default'); if (isset($config->model_namespace)) { $namespace = $config->model_namespace; } if ($namespace === null) { $namespace = 'Models'; } } $modelClass = Str::singularize($table->name); $modelClass = Str::camelCaps($namespace . '\\' . $modelClass); if (!class_exists($modelClass)) { $modelClass = Model::class; } return static::$modelClassCache[$table->name] = $modelClass; }