我有一个Livewire组件,它直接在属性模型中绑定一个名为department_id的属性。问题是,我既没有定义模型属性cast department_id => integer,也没有定义它,我的Livewire组件将其存储为string,而不是从前端接收到的integer。
下面是phpdebugbar转储的整个livewire组件的屏幕截图。

因此,我的问题是,如何将直接位于模型属性内部的string integer__数据绑定到数据中?
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\User;
class Form extends Component
{
public User $user;
protected $rules = [
'user.department_id' => ['nullable', 'integer'],
];
public function render()
{
return view('livewire.form');
}
public function save()
{
$this->validate();
$this->user->save();
}
}<!-- /resources/views/livewire/form.blade.php -->
<select name="department-id" id="department-id" wire:model.lazy="user.department_id">
<option value="1" {{ $user->department_id == 1 ? 'selected' : '' }}>Department #1</option>
<option value="2" {{ $user->department_id == 2 ? 'selected' : '' }}>Department #2</option>
<option value="3" {{ $user->department_id == 3 ? 'selected' : '' }}>Department #3</option>
</select>发布于 2021-01-23 17:17:44
您可以通过在用户模型上设置$casts属性在模型上强制转换该属性。最初,从数据库中检索到的所有数据都是字符串,您必须具体地对其进行强制转换。
protected $casts = [
'department_id' => 'integer',
];发布于 2022-11-24 12:00:38
输入的值总是字符串。即使是来自<input type="number">的值,但您不必担心它,因为Laravel和数据库为您处理它。
如果在保存模型id时传递字符串"3",则它将正确地存储为整数,因为数据库中的列类型是整数。
https://stackoverflow.com/questions/65859267
复制相似问题