【问题标题】:Laravel Update Multiple Records with Different Values for Each RecordLaravel 更新多条记录,每条记录具有不同的值
【发布时间】:2021-09-23 08:13:07
【问题描述】:

我想为每条记录更新具有不同值的多条记录。我应该如何处理 laravel 雄辩?这是我的代码示例。提前致谢。

    $employee_presences = Employee_presence::
    where('employee_id', $report_history->employee_id)
    ->whereBetween('presence_date',[$report_history->report->start_period,$report_history->report->end_period])
    ->get();

    foreach ($presences_data as $presence_data) 
    {
        foreach ($employee_presences as $employee_presence)
        {
            $updated_presences = Employee_presence::
            where('id', $employee_presence->id)->update([
                'presence_value' => $presence_data['presence_value']
            ]);
        }
    }

这些是 $presences_data 中的值。这是用于更新记录的新数据。

这些是记录$employee_presences

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    无法在同一查询中更新具有不同数据的多条记录。 您可以通过对每组更改运行一个查询来批量更新您的记录:

    Employee_presence::whereIn('employee_id', <list of ids>)->update(
        [
            'presence_value' => 1,
            'presence_date' => "2021-07-12"
        ]
    );
    
    Employee_presence::whereIn('employee_id', <different ids>)->update(
        [
            'presence_value' => 0.5,
            'presence_date' => "2021-07-13"
        ]
    );
    

    如果没有组(意味着每条记录都有不同的值),您需要在不同的查询中分别更新它们。效率不高。

    【讨论】:

      【解决方案2】:

      可以通过使用 mysql CASE 语句来实现。 AFAIK 在 eloquent 或 case 语句的查询构建器中没有内置函数,因此您必须使用原始语句来完成查询的那部分。

      我真的不明白你在你的例子中想要哪个记录的值(可能是我的错),但我会尽力帮助你使用一个你可以使用的函数:

      假设您从要更新的员工中选择了一组员工 ID,并且对于每个员工 ID,您还知道要赋予他们的出席值。您可以创建一个数组$data,其中这些 id 是键,存在值是值。 那么您可以将该数组放入以下函数中:

      public static function updatePresencePerEmployee($data){
          //make the complex case statement first
          $case = "(case";
          foreach ($data as $employee_id => $presence_value ){
              $case.=" when employee_id = ".$employee_id." then ".$presence_value;
          }
          $case.=" end)";
      
          DB::table('employee_presence')
              //shift the keys of the array which are employee id's to values so laravel can use it in the whereIn clause
              ->whereIn('employee_id', array_keys($data))
              //dont forget to throw the case string in to the DB:raw function
              ->update(['presence_value' =>DB::raw($case)]);
      }
      

      我在我的一个应用程序中使用了这个功能,但它需要改进。 例如,现在您需要确保 case 语句中的这些值不是 sql 注入。

      如果您不明白会发生什么,阅读此主题会有所帮助。它告诉你如何使用 case 语句。

      MySQL - UPDATE multiple rows with different values in one query

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多