Laravel Livewire更新wire:modal时报Invalid column name 'id'错误
问题根因
你遇到的报错是Livewire组件hydration(状态重构)阶段的典型问题:
你将Eloquent集合直接存到了组件的公共属性$items和$subItems中,Livewire在首次渲染后会将这些模型的主键序列化到前端状态,当后续触发任何组件交互(比如更新搜索内容、再次点击搜索按钮)时,Livewire会自动尝试用主键从数据库重新查询对应的模型来恢复组件状态,这时候出现了查询id字段的错误,说明主键识别异常。
解决方案
方案1(最稳妥,优先使用):将集合转为普通数组存储
避免Livewire自动触发模型查询,直接把查询结果转为数组后再赋值给公共属性,修改Livewire组件代码:
// 先修改属性默认值 public $items = []; public $subItems = []; public function search() { $this->items = []; $this->subItems = []; if ($this->search) { $this->items = Test::where('ItemNo', $this->search)->get()->toArray(); if (!empty($this->items)) { $this->warning = false; $this->message = ''; $this->subItems = TestSubItems::where('ItemNo', $this->search)->get()->toArray(); } if (empty($this->items)) { $this->message = 'Not found'; } } }
对应修改Blade视图中的判断逻辑:
- 把
@if (!$items->isEmpty())改为@if (!empty($items)) - 把
@if (!$subItems->isEmpty())改为@if (!empty($subItems)) - 遍历数组时属性访问改为数组形式,比如
{{ $item['code'] }}、{{ $item['itemNo'] }}
方案2:检查模型配置并清除缓存
如果你需要保留Eloquent集合作为公共属性,按以下步骤排查:
- 确认
Test、TestSubItems两个模型都正确配置了自定义主键、主键类型、是否自增属性,且$primaryKey的大小写完全匹配数据库表中的字段名(SQL Server对字段大小写敏感) - 执行命令清除Laravel缓存,避免旧的模型配置残留:
php artisan optimize:clear
方案3:禁用Livewire的模型自动重构(仅适用于Livewire 3)
如果确实需要存储模型实例到公共属性,可以给属性加#[Locked]注解,禁止Livewire在hydration阶段自动查询模型:
use Livewire\Attributes\Locked; #[Locked] public $items = null; #[Locked] public $subItems = null;
内容的提问来源于stack exchange,提问作者Doc9
相关产品推荐
相关产品推荐

