安装后未显示特定行的 Livewire 模型值

Livewire model value for a specific row is not showing after mount

对于不同的 rows/stations 我有不同的位置(由于篇幅原因没有把整个 table 放在一起)我想实时更新这些值。他们进入一个枢轴 table 并且编辑有效,但我不确定如何显示数据库中已有的点。它们似乎在刷新时出现了一秒钟,但随后消失了,而且,当我尝试编辑多行时,我不确定如何清空数组,这样它就不会有以前的值而不会弄乱其余的值的斑点。

@foreach($selected_stations as $key => $selected_station)
<td class="border px-4 py-2">
                    <input name="spot[{{$selected_station->id}}]"  wire:model="spot.{{$selected_station->id}}" wire:change="updatespot({{$selected_station->id}})" type="text" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500" value="{{$current_workbook->stations()->find($selected_station->id)->pivot->spot}}">
</td>
@endforeach

这是我的 livewire 组件

public $spot;
public $spot_value;
public $selected_stations;
public $current_workbook;

public function mount($client, $workbook){
        $this->selected_stations= $workbook->stations;
        $this->current_workbook = Workbook::find($this->workbook_id);
        foreach($this->selected_stations as $key => $selected_station){
            $this->spot = $this->current_workbook->stations()->find($selected_station->id)->pivot->spot;
        }

    }
public function updatespot(Request $request, $station_id){
        $this->spot_value = implode(", ", $this->spot);
        // dd($this->spot_value);
        $this->current_workbook->stations()->updateExistingPivot($station_id, ['spot'=>$this->spot_value]);
    }

这是显示的错误,因为我没有清除数组

Warning: 1265 Data truncated for column 'spot' at row 1 (SQL: update station_workbook set spot = 99, 45, updated_at = 2021-08-11 19:56:10 where station_workbook.workbook_id = 47 and station_id in (18))

您只需要在前端使用 wire:model 属性即可 render/update 点值。这是一个简化的组件示例:

public $workbook;
public $stations;
public $spots;

public function mount($workbook)
    $this->stations= $workbook->stations;
    
    // This will give you an array of spots keyed by station id
    $this->spots = $this->stations->pluck('pivot.spot', 'id')->all();
}

// ...

/**
 * Here we leverage a Livewire Lifecycle hook to
 * detect when our $spots variable has been updated.
 * 
 * This helpfully passes us the new value and the
 * corresponding key, in this case our station id
 */
public function updatedSpots($value, $key){
    $this->workbook->stations()
        ->updateExistingPivot($key, ['spot' => $value]);
}

那么这在前端是如何工作的呢?我们在输入中所需要的只是绑定到 $spots 数组中特定键的 wire:model 属性:

@foreach($stations as $station)
    <td class="border px-4 py-2">
        <input type="text" wire:model="spots.{{ $station->id }}" class="...">
    </td>
@endforeach

这会针对每个输入进行实时更新。 Livewire 有一个 built in debounce of 150ms 用于 wire:model,但可以增加延迟以尽量减少对数据库的请求:

<input type="text" wire:model.debounce.500ms="spots.{{ $station->id }}" class="...">