Код: Выделить всё
-- Mapping configuration table
CREATE TABLE `campos_prompt` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`nombre_original` varchar(255) NOT NULL, -- original field name shown in JSON prompt (e.g. “PROVEEDOR - RAZÓN SOCIAL”)
`nombre_personalizado` varchar(255) DEFAULT NULL,-- optional custom display name
`nombre_interno` varchar(255) DEFAULT NULL, -- actual DB column name (snake_case)
`orden` int(11) NOT NULL DEFAULT 0,
`visibilidad` tinyint(1) NOT NULL DEFAULT 1,
`grupo` varchar(20) DEFAULT 'general',
`descripcion` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
-- Destination table where data should be stored
CREATE TABLE `datos_prompt` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`id_documento` int(11) NOT NULL, -- foreign key to files table
`proveedor_razon_social` varchar(255) DEFAULT NULL, -- supplier name
`proveedor_direccion` varchar(255) DEFAULT NULL, -- supplier address
`proveedor_cif` varchar(50) DEFAULT NULL, -- supplier tax ID
`cliente_razon_social` varchar(255) DEFAULT NULL, -- client name
`cliente_direccion` varchar(255) DEFAULT NULL, -- client address
`cliente_cif` varchar(50) DEFAULT NULL, -- client tax ID
`factura_numero` varchar(50) DEFAULT NULL, -- invoice number
`factura_fecha` varchar(50) DEFAULT NULL, -- invoice date
`factura_fecha_vencimiento` varchar(50) DEFAULT NULL,-- due date
`factura_total` varchar(50) DEFAULT NULL, -- invoice total
`moneda` varchar(10) DEFAULT NULL, -- currency code
`iva_porcentaje` varchar(10) DEFAULT NULL, -- VAT rate
`iva_total` varchar(50) DEFAULT NULL, -- total VAT amount
`iva_0_base` varchar(50) DEFAULT NULL,
`iva_0_cuota` varchar(50) DEFAULT NULL,
`iva_4_base` varchar(50) DEFAULT NULL,
`iva_4_cuota` varchar(50) DEFAULT NULL,
`iva_10_base` varchar(50) DEFAULT NULL,
`iva_10_cuota` varchar(50) DEFAULT NULL,
`iva_21_base` varchar(50) DEFAULT NULL,
`iva_21_cuota` varchar(50) DEFAULT NULL,
`retencion_porcentaje` varchar(10) DEFAULT NULL, -- withholding rate
`retencion_cuota` varchar(50) DEFAULT NULL -- withholding amount
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
Код: Выделить всё
namespace App\Models;
use CodeIgniter\Model;
class DatosPromptModel extends Model
{
protected $table = 'datos_prompt';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $useTimestamps = false;
// These exactly match the column names defined above
protected $allowedFields = [
'id_documento',
'proveedor_razon_social',
'proveedor_direccion',
'proveedor_cif',
'cliente_razon_social',
'cliente_direccion',
'cliente_cif',
'factura_numero',
'factura_fecha',
'factura_fecha_vencimiento',
'factura_total',
'moneda',
'iva_porcentaje',
'iva_total',
'iva_0_base',
'iva_0_cuota',
'iva_4_base',
'iva_4_cuota',
'iva_10_base',
'iva_10_cuota',
'iva_21_base',
'iva_21_cuota',
'retencion_porcentaje',
'retencion_cuota'
];
public function getAllowedFields()
{
return $this->allowedFields;
}
public function getDatosPorArchivo($nombreArchivo)
{
// ... code to fetch stored rows ...
}
}
Код: Выделить всё
// …after decoding JSON:
// $datos = json_decode($json, true);
// --- NEW: Save to database ---
if ($id_documento && is_array($datos)) {
try {
file_put_contents($log, "Saving to DB for document ID $id_documento\n", FILE_APPEND);
$datosPromptModel = new \App\Models\DatosPromptModel();
$camposModel = new \App\Models\CamposPromptModel();
// 1. Build map from JSON field name → DB column (normalized keys)
$campos = $camposModel->getCamposVisiblesOrdenados();
$mapaCampos = [];
foreach ($campos as $campo) {
// nombre_original is what appears in the JSON,
// nombre_interno is the snake_case column name
$nameJson = $campo['nombre_personalizado'] ?: $campo['nombre_original'];
$nameInternal = $campo['nombre_interno'];
$mapaCampos[ normaliza($nameJson) ] = $nameInternal;
}
file_put_contents($log, "Field map: " . print_r($mapaCampos, true), FILE_APPEND);
// 2. Prepare insert data
$datosPromptData = ['id_documento' => $id_documento];
foreach ($datos as $k => $v) {
if ($k === 'LÍNEAS DE PRODUCTO') continue;
$kn = normaliza($k);
if (isset($mapaCampos[$kn])) {
$datosPromptData[ $mapaCampos[$kn] ] = $v;
} else {
file_put_contents($log, "Unmapped field: $k\n", FILE_APPEND);
}
}
file_put_contents($log, "Raw insert data: " . print_r($datosPromptData, true), FILE_APPEND);
// 2.1 Get allowedFields from model
$allowed = $datosPromptModel->getAllowedFields();
file_put_contents($log, "AllowedFields: " . print_r($allowed, true), FILE_APPEND);
// 2.2 Filter only valid keys
$insertData = array_intersect_key(
$datosPromptData,
array_flip($allowed)
);
file_put_contents($log, "Filtered insert data: " . print_r($insertData, true), FILE_APPEND);
// 2.3 Insert!
$id_datos_prompt = $datosPromptModel->insert($insertData);
file_put_contents($log, "Inserted ID: $id_datos_prompt\n", FILE_APPEND);
// … then save product lines …
} catch (\Throwable $e) {
file_put_contents($log, "DB error: " . $e->getMessage() . "\n", FILE_APPEND);
}
} else {
file_put_contents($log, "No data to save (invalid document ID or data)\n", FILE_APPEND);
}
Raw insert data: Array
(
[id_documento] => 686
[proveedor_razon_social] => EMPRESA PRUEBA, S.L.
[proveedor_direccion] => C/PLAZA CIES, 14 18600 MOTRIL
[proveedor_cif] => B00064000
[cliente_razon_social] => EMPRESA PRUEBA2
[cliente_direccion] => CALLE EVARISTO GARCIA
[cliente_cif] => B50006000
[factura_numero] => 01
[factura_fecha] => 18-05-2025
[factura_fecha_vencimiento] =>
[factura_total] => 1.539,03 €
[moneda] => €
[iva_porcentaje] => 10,00%
[iva_total] => 139,91 €
[iva_10_base] => 1.399,12 €
[iva_10_cuota] => 139,91 €
… other fields …
)
AllowedFields: Array
(
[0] => id_documento
[1] => PROVEEDOR - RAZÓN SOCIAL ← these appear as uppercase, with mojibake
[2] => PROVEEDOR - DIRECCIÓN
[3] => PROVEEDOR - CIF
[4] => CLIENTE - RAZÓN SOCIAL
[5] => CLIENTE - DIRECCIÓN
[6] => CLIENTE - CIF
[7] => FACTURA - NÚMERO
…
[23] => RETENCIÓN - CUOTA
)
Filtered insert data: Array
(
[id_documento] => 686
)
→ Only `id_documento` survives, all other keys are discarded even though they match the actual column names in `$allowedFields`. AND THE PRODUCT LINES ARE INSERTED WITHOUT ANY PROBLEM
< /code>
Почему Codeigniter 4 отбрасывает все ключи, кроме Document_id, хотя $ insertdata содержит все другие столбцы, перечисленные в $ Aldfields? строчная змея_ас. Может ли это указывать на проблему кодирования или переопределение свойства $ AldFields?>
Подробнее здесь: https://stackoverflow.com/questions/796 ... he-columns
Мобильная версия