【问题标题】:Laravel how to update value in mysql only if value is changedLaravel如何仅在值更改时更新mysql中的值
【发布时间】:2017-04-24 14:12:54
【问题描述】:

我是 Laravel 的新手。我要做的只是如下:

我的表单中有一些字段,例如 TITLE、DESCRIPTION

TITLE字段在数据库中是唯一的。

这是我为更新我的价值观所做的。

$product              = Product::find($id); 
$product->title       = $request->title;
$product->description = $request->description;
$product->save();

但这会产生错误(该值已经存在),因为我的 TITLE 字段是唯一的。

我只想在 TITLE 值更改时更新我的​​ TITLE,否则更新相同的值但更新其他字段。谢谢

【问题讨论】:

标签: php mysql laravel laravel-5.3


【解决方案1】:

这样的?

$product = Product::find($id);

if ($product->title == $request->title) {
    $product->description = $request->description;
} else {
    $product->title = $request->title;
}

$product->save();

【讨论】:

  • 我想更新由 id 给出的特定行。我认为上面的函数会改变任何标题匹配的行。就是这样。谢谢
  • 请检查更新的答案。您将从 DB 中获得该行。然后您将检查标题是否已更改。如果标题已更改,它将仅更新标题。如果没有,它只会更新描述。您正在寻找这种行为吗?
【解决方案2】:

您发布的代码完全(如果间接地)按照您所说的去做。您的问题是另一个问题:您正在分配一个在其他地方使用的标题,因此违反了唯一性。

您必须确认 new 标题尚未使用。

$duplicate = Product::where('title', '=', $request->title)->where('id', '!=', $id)->first();

此时不清楚你想做什么

a) 您要使用重复记录代替$id 指示的记录吗?

b) 这是一个错误吗?

c) 是否应该更新 $id 记录,只保留标题?

你可以做任何这些事情;您不能做的是“仅在 TITLE 值更改时更新我的​​ TITLE”,因为更改后的值已在其他地方使用。

【讨论】:

    【解决方案3】:

    我没有看到你的任何数据库结构或表单代码,只有你所说的小sn-p。

    你可以做这样的事情......

    $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
         }
    

    抱歉简短而甜蜜,离开去办公室并认为现在发帖可能会有所帮助。让我知道我是否在错误的轨道上并且在我可以帮助的地方提供帮助。

    【讨论】:

      【解决方案4】:

      您可以使用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();
      

      【讨论】:

        【解决方案5】:

        你应该看看 Laravel 中的 wasChanged() 函数。

        【讨论】:

        猜你喜欢
        • 2021-04-21
        • 2015-01-02
        • 2013-04-13
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        • 1970-01-01
        • 2016-03-15
        • 2021-07-29
        相关资源
        最近更新 更多