I'm trying to make an autoincrement code with date and it will reset the code on the other day.
I have this migration.
public function up()
{
Schema::create('records', function (Blueprint $table) {
$table->id();
//other codes here...
});
}
Then, I add column that will auto increment 5 digits using
ALTER TABLE id ADD my_id AS RIGHT('00000' + CAST(id AS VARCHAR(5)) , 5) PERSISTED
I have this query on my controller
public function get_records(Request $request){
$records = DB::table('records')->select(
'records.my_id',
//other codes here...
)
->get();
$recordlist = [];
$currentMonth = Carbon::now()->format('mm');
$currentDay = Carbon::now()->format('dd');
foreach($records as $data):
$data->CODE = 'Z' . $currentMonth . $currentDay . '-' .$data->my_id;
$recordlist[] = $data;
endforeach;
return recordlist;
// OUTPUT --> CODE: 'Z0331-0001'
}
I would like my output like..
today is 03/31
CODE:
Z0331-00001
Z0331-00002
Z0331-00003
.....
Z0331-00010
Z0331-00011
Z0331-00012
.....
Z0331-00100
Z0331-00101
Z0331-00102
//The other day(04/01)..
CODE:
Z0401-00001
Z0401-00002
Z0401-00003
.....and so on
I just come up with this transaction.
I just add table,
ALTER TABLE records DROP COLUMN my_id
ALTER TABLE records ADD my_id VARCHAR(5) NOT NULL
Then, my query is..
$createdrecord = //last created record ex(CODE: 'Z0330-00265' created_at: '03/30(yesterday)' )
$today = Carbon::now();
foreach($records as $data){
if($today != $createdrecord){
$data->my_id = '00000';
}else{
$data->my_id += 1;
}
}
I think this will OK, But my code doesn't go well..
Thank for your help.