Good morning or nights for some. The following block of code works correctly and is written in PHP with the help of the Yii2 framework:
$subQuery = (new \yii\db\Query)
->select([
'p.FK_DOCUMENTO_ODC',
])
->from('tbl_periodos p')
->where(['YEAR(p.FECHA_INI)'=>intval($fecha_ini_anio)])
->andWhere(['not', ['p.FK_DOCUMENTO_ODC' => null]])
->orderBy('p.FK_DOCUMENTO_ODC DESC')->limit(1)->one();
$query = (new \yii\db\Query)
->select([
'd.PK_DOCUMENTO',
'd.MONTO',
'd.NUMERO_PERIODOS',
])
->from('tbl_documentos d')
->where(['=','d.PK_DOCUMENTO',$subQuery['FK_DOCUMENTO_ODC']])
->orderBy('d.PK_DOCUMENTO DESC')->limit(1)->one();
if($query){
$mismo_pkDocumento = Tblperiodos::find()->where(['FK_DOCUMENTO_ODC' => $query['PK_DOCUMENTO']])->all();
$cont_num_doc = count($mismo_pkDocumento);
if($cont_num_doc < $query['NUMERO_PERIODOS']){
$modelDoc = TblDocumentos::find()->where(['PK_DOCUMENTO' => $query['PK_DOCUMENTO']])->limit(1)->one();
$nuevo_monto = $monto + $query['MONTO'];
$modelDoc->MONTO = $nuevo_monto;
$modelDoc->save(false);
$fecha_fin_nueva = transform_date($fechaFin,'Y-m-d');
$model->FECHA_INI=transform_date($fechaInicio,'Y-m-d');
$model->FECHA_FIN=$fecha_fin_nueva;
$model->TARIFA=$tarifa;
$model->HORAS=$horas;
$model->MONTO=$monto;
$model->FK_DOCUMENTO_ODC=$query['PK_DOCUMENTO'];
$model->FK_ASIGNACION=$keyAsig;
$model->FK_EMPLEADO=$asignacion->FK_EMPLEADO;
$model->FECHA_INGRESO=date('Y-m-d H:i:s');
$model->save(false);
if ($fecha_fin_nueva > $asignacion->FECHA_FIN) {
$asignacion->FECHA_FIN = $fecha_fin_nueva;
$asignacion->save(false);
}
}
}
Likewise within the SP I can leave the query in this way:
SELECT * FROM tbl_documentos d WHERE d.PK_DOCUMENTO = (SELECT p.FK_DOCUMENTO_ODC FROM tbl_periodos p WHERE YEAR(p.FECHA_INI) = YEAR(FECHA_INI_ANIO) AND p.FK_DOCUMENTO_ODC IS NOT NULL ORDER BY p.FK_DOCUMENTO_ODC DESC LIMIT 1) ORDER BY d.PK_DOCUMENTO DESC LIMIT 1
And this is where I have the doubt of how to save in a variable that query in the SP to be able to make the previous comparisons, if I found a register, count the found ones etc.