简体   繁体   中英

How to find if record is created or updated in updateOrCreate function?

I've a simple post form. Records are saved to database with updateOrCreate function.

I've following records to be stored,

  1. user_id
  2. product_id
  3. review
  4. rating

After submitting form, user_id and product_id are used to check if record exist or not. If exist, record will be updated otherwise new record created with the function.

public function updateOrCreate($input)
{
    return $this->model->updateOrCreate(['product_id'=> $input['product_id'],'user_id'=>$input['user_id']],['rating'=>$input['rating'],'review'=>$input['review']]);
}

Is there any built in method to find new record created or existing record updated ?

Any kind of suggestion is appreciated.

You need to determine if the model or given attribute(s) have been modified. And wasChanged() method will help to identify if the model is updated or not.

$model = $this->model->updateOrCreate(['product_id'=> $input['product_id'],'user_id'=>$input['user_id']],['rating'=>$input['rating'],'review'=>$input['review']]);

// It will return true if the record have been modified
$wasChanged = $model->wasChanged();
if ( $wasChanged ) {
    // updated
}
else {
   // created
}

Hope this help you.

There is a public property on Eloquent models called $wasRecentlyCreated . It is set when an insert is performed . And it will only be true after an insert for the same request; not for consecutive requests. If an update has been performed, it will be false .

Be aware that the property is also only true for the exact same model instance. If you reload the model with Product::find($id) , it will be false . What happens if you call refresh() on a model, is unfortunately unclear to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM