[英]Laravel how to update value in mysql only if value is changed
我是Laravel的新手。 我所要做的就是如下:
我的表格中有一些字段,如TITLE,DESCRIPTION 。
TITLE字段在数据库中是唯一的。
这就是我为更新我的价值所做的工作。
$product = Product::find($id);
$product->title = $request->title;
$product->description = $request->description;
$product->save();
但是这会给出错误(该值已经存在),因为我的TITLE字段是唯一的。
我想要的只是在TITLE值改变时更新我的TITLE,否则更新相同的值但更新其他字段。 谢谢
像这样的东西?
$product = Product::find($id);
if ($product->title == $request->title) {
$product->description = $request->description;
} else {
$product->title = $request->title;
}
$product->save();
您发布的代码确实(如果是间接的)您所说的内容。 你的问题是另一个问题: 你正在分配一个在别处使用的标题 ,从而违反了唯一性。
您必须验证新标题尚未使用。
$duplicate = Product::where('title', '=', $request->title)->where('id', '!=', $id)->first();
目前还不清楚你想做什么 :
a)你想使用重复记录而不是 $id
指示的记录吗?
b)这是一个错误吗?
c)是否应该更新$id
记录,仅保留标题?
你可以做任何这些事情; 你不能做的是“仅在更改TITLE值时更新我的标题”,因为更改的值已在其他地方使用。
我没有看到你的任何数据库结构或表单代码只是你上面提到的小片段。
你可以这样做......
$checkTitle = Product::where('title', '=', $request->input('title')->first();
你也可以......
$record = Product::find($id)
if($request->input('title') === $record->title){
// Record with the $id has the same title as you are posting in the request.
}else{
// Title for $id lets say id number 3, Is not the same as the form request you are sending so now Perform insert
}
if(count($checkTitle) >= 1){
// Means the title exists and do what ever you want...
// Perform update
}else{
// Perform insert
}
对不起,简短而甜蜜,离开去办公室,并认为现在发布可能会有所帮助。 如果我在错误的轨道上并且在可能的地方帮助我,请告诉我。
您可以使用if
语句来检查天气列值是否与原始值相同?
$currentProduct = Product::find($id);
//Check and update if title not same
if($currentProduct->title == $request->title){
$currentProduct->description = $request->description;
}
//Update title and description...
else {
$currentProduct->title = $request->title;
$currentProduct->description = $request->description;
}
$currentProduct->save();
你应该看看Laravel中的wasChanged()函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.