简体   繁体   English

如何查找是否在updateOrCreate函数中创建或更新记录?

[英]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. 记录通过updateOrCreate函数保存到数据库中。

I've following records to be stored, 我正在跟踪要存储的记录,

  1. user_id 用户身份
  2. product_id PRODUCT_ID
  3. review 评论
  4. rating 评分

After submitting form, user_id and product_id are used to check if record exist or not. 提交表单后,使用user_idproduct_id来检查记录是否存在。 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. wasChanged()方法将有助于识别模型是否已更新。

$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 . $wasRecentlyCreated模型上有一个名为$wasRecentlyCreated的公共财产。 It is set when an insert is performed . 进行插入时设置。 And it will only be true after an insert for the same request; 并且只有在插入相同请求后,它才会为true not for consecutive requests. 不适用于连续的请求。 If an update has been performed, it will be false . 如果执行了更新,则将为false

Be aware that the property is also only true for the exact same model instance. 请注意,该属性也仅对于完全相同的模型实例为true If you reload the model with Product::find($id) , it will be false . 如果使用Product::find($id)重新加载模型,则它将为false What happens if you call refresh() on a model, is unfortunately unclear to me. 不幸的是,如果您在模型上调用refresh() ,会发生什么呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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