0
When records are entered within a loop
and is made a select
to get the last record based on a conditional, after the fifth interaction he no longer takes the last record and keeps picking up the fifth.
I’m using Laravel
with the bank MySQL
and I have a table with the fields:
- id
- code
- cliente_id
- date
- sequential
The year sequence will be used to assemble a code based on the year and the sequence as for example:
- FC124/2018
- FC125/2018
- FC1/2019
- FC2/2019
- FC3/2019
My algorithm follows the following steps:
- Save a new record with cliente_id and date. (id is autonumbering)
- Take the max of sequential_year of a given year
- Sum +1
- Assemble code based on these values. Ex. If the 2019 maximum sequential_year is 3 then it will generate FC4/2019 code
- Update code and sequential year in the record.
The code below is the method that generates the new code and updates it in the record. The variable $Insert already owns the obj with the current record that was inserted to be able to update.
This method is called inside a loop that inserts a record and calls the method gerarCodigo() passing the entered record.
public function gerarCodigo($insert)
{
$ultimoNumeroAno = \App\Ficha::where(
DB::Raw('year(data)'), date('Y')
)->max('sequencial_ano');
$numero_ano = $ultimoNumeroAno + 1;
$codigo = 'FC'.($numero_ano).'/'.date('Y');
$insert->update(
['codigo' => $codigo,
'sequencial_ano' => $numero_ano
]
);
Until the fifth interaction sequencial_ano
is picked up correctly, but then always keeps catching the 5 repeated and repeated on average.
Does anyone know why? Is there any better way to get the last sequencial_ano
one-year?
Note: I’ve also tried using with order_by('id', 'desc')->first()
and gave in the same
could be recorded only the sequence number of the year will facilitate at the time of adding + 1 and then if it will have to show FC writes in a field or only show when it is displaying
– novic
Thanks, but I found that I was using the current year even when the generated form had a date from another year. I posted an answer explaining everything.
– Bruno Passos