Concurrent insert if model not found

Hi,

I have a problem with concurrent insert (if not exists). In my project I using mysql database.

Situation:
Android application call 2 endpoints (async) to my yii2 api. Mostly in same time.

First endpoint upload image (and save filename and size to File AR)
Second endpoint send data to create message (and save some additionall data to File AR)

Both of those endpoints, first trying load File AR (by column file - unique) and create and save new AR if does not exist.

There are relevant fragments of function, that both endpoints use:

  $model = File::find()
            ->where(['file'=>$file])
            ->limit(1)
            ->one();

  if (!$model) {
            $model = new File();
            $model->file =$file;
}
$model->save();

Sometimes after save() mysql throw Intergrity exception: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘19912-19912-20190806_214104.jpg’ for key ‘file’

Any tips how to solve this?

Thanks