Eloquent - 使用 foreach 循环更新 eloquent 关系

Eloquent - Update eloquent relations with foreach loop

我有一个控制器功能可以发送多个设备进行维修(本质上是针对多个现有 devices_repairs 记录的更新请求)。当我尝试从设备 table 中检索设备以及维修详细信息(设备 table、devices_repairs table)时,记录被检索但是当我尝试更新values 更新请求不保存新数据。

这是我的控制器功能:

<?php
    public function sendMultiDevicesForRepair(sendDeviceForRepairRequest $request) {
        $request->validated();

       $device_barcodes = ["BSC0626", "BSC0376"];
       $devices = Devices::with('repairDetails')->whereIn('barcode',$device_barcodes)->get();

            DB::transaction(function () use (&$devices) {
               foreach($devices as $device) {
                    $device->repairDetails->repair_date_sent_for = request('repair_date_sent_for');
                    $device->repairDetails->job_number = request('jobNumber'.$device->barcode);
                    $device->repairDetails->operator_date_sent = Carbon::now()->toDateTimeString();
                    $device->repairDetails->operator_sent_by = getCreatedUpdatedBy();
                } 
            });

            $devices->push();

            // perform a redirect if the transaction is successful
            return redirect('/devices/repair')
                ->with('success', 'The devices: '  . request('deviceBarcodes') . ' have been sent for repair.');
    }
?>

当我在循环中更改修复细节后执行 (dd($devices)) 时,属性数组具有新值,但即使没有返回错误,push() 也不会更新数据库:

Illuminate\Database\Eloquent\Collection {#1439 ▼
  #items: array:2 [▼
    0 => App\Devices {#1446 ▼
      +timestamps: false
      #table: "devices"
      #primaryKey: "device_id"
      
      #relations: array:1 [▼
        "repairDetails" => App\DevicesRepairs {#1451 ▼
          #table: "devices_repairs"
          #primaryKey: "device_id"
          #attributes: array:15 [▼
            "device_id" => "54"
            "repair_damaged_by" => "157"
            "repair_damage_type" => "Screen Damage"
            "repair_date_received" => "2020-02-26"
            "repair_date_sent_for" => "2022-03-31"
            "repair_damage_notes" => "Cracked Screen - due to age not worth repairing"
            "repairer_name" => null
            "repair_is_user_damage" => "1"
            "job_number" => "1000.5312.9745"
            "operator_date_received" => "2020-02-26 00:00:00"
            "operator_received_by" => "56"
            "operator_date_sent" => "2022-03-31 16:30:11"
            "operator_sent_by" => "41"
            "photo_id" => null
            "photo_id_back" => null
          ]
          #original: array:15 [▼
            "device_id" => "54"
            "repair_damaged_by" => "157"
            "repair_damage_type" => "Screen Damage"
            "repair_date_received" => "2020-02-26"
            "repair_date_sent_for" => null
            "repair_damage_notes" => "Cracked Screen - due to age not worth repairing"
            "repairer_name" => null
            "repair_is_user_damage" => "1"
            "job_number" => null
            "operator_date_received" => "2020-02-26 00:00:00"
            "operator_received_by" => "56"
            "operator_date_sent" => null
            "operator_sent_by" => null
            "photo_id" => null
            "photo_id_back" => null
          ]
          #changes: []

这是我的模型。 设备型号:

class Devices extends Model
{
    /**
     * @var bool $timestamps Disable timestamps
     */
    public $timestamps = false;
    /**
     * @var string $table Name of the db table
     */
    protected $table = 'devices';
    /**
     * @var string $primaryKey Name of the primary key
     */
    protected $primaryKey = 'device_id';
    /**
     * @var array $fillable The attributes that are mass assignable.
     */
    protected $fillable = [
        'status',
        'order_reference',
        'model',
        'serial',
        'imei',
        'barcode',
        'mobile_number',
        'helpdesk_url_id',
        'device_notes'
    ];

    use Searchable;

    function repairDetails() {
        return $this->hasOne(DevicesRepairs::class, 'device_id');
    }
}

DevicesRepairs 型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DevicesRepairs extends Model
{
    use HasFactory;
    protected $table = 'devices_repairs';
    protected $primaryKey = 'device_id';
    public $timestamps = false;

    function device() {
        return $this->hasOne(Devices::class, 'device_id');
    }
    
}

我做错了什么?我使用单独的 DB::Table 更新查询进行了此操作,但我更喜欢使用 eloquent.

您需要将数据推送到 foreach 循环中

而不是

DB::transaction(function () use (&$devices) {
               foreach($devices as $device) {
                    $device->repairDetails->repair_date_sent_for = request('repair_date_sent_for');
                    $device->repairDetails->job_number = request('jobNumber'.$device->barcode);
                    $device->repairDetails->operator_date_sent = Carbon::now()->toDateTimeString();
                    $device->repairDetails->operator_sent_by = getCreatedUpdatedBy();
                } 
            });

            $devices->push();

使用这个

DB::transaction(function () use (&$devices) {
                   foreach($devices as $device) {
                        $device->repairDetails->repair_date_sent_for = request('repair_date_sent_for');
                        $device->repairDetails->job_number = request('jobNumber'.$device->barcode);
                        $device->repairDetails->operator_date_sent = Carbon::now()->toDateTimeString();
                        $device->repairDetails->operator_sent_by = getCreatedUpdatedBy();
                        $device->push(); // save data here
                    } 
                });