You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Livewire中如何根据下拉选项获取关联配送费用数据?

问题描述

我有一张名为delivery_fees的数据库表,包含三个字段:

  • destination:目的地
  • domicile:上门配送金额
  • stopdesk:邮局配送金额

我通过以下代码获取所有目的地,并用带wire:model="wil"的下拉菜单在视图展示:

$destination = DB::table('delivery_fees')->select('destination')->pluck('destination');

需求是:用户选择某个destination时,获取对应的domicile和stopdesk值。我尝试用下面的查询,却抛出错误SQLSTATE[HY093]: Invalid parameter number:

$fees = DB::table('delivery_fees')->select('stopdesk', 'domicile')->where('destination','like',$destination)->get();

注:执行dd($destination)得到的是包含所有目的地值的集合。


问题原因与解决方法

原因分析

你错误地把所有目的地的集合传给了where条件的第三个参数。$destination是pluck返回的集合,不是用户当前选择的单个目的地值,这导致SQL查询参数不匹配,触发HY093错误。

正确实现步骤

  1. 获取用户选择的目的地
    Livewire的wire:model="wil"会把用户选择的值绑定到组件的$wil属性,你应该用这个属性作为查询条件,而非之前的$destination集合。

  2. 修正查询代码

// 当$wil有值时执行查询
if ($this->wil) {
    $fees = DB::table('delivery_fees')
        ->select('stopdesk', 'domicile')
        ->where('destination', $this->wil) // 直接匹配选中的目的地,无需like(除非是模糊匹配场景)
        ->first(); // 用first()获取单条记录,因为每个destination对应唯一的费用记录
}
  1. 模糊匹配场景(可选)
    如果确实需要用like进行模糊匹配(比如目的地包含关键词),需拼接通配符:
$fees = DB::table('delivery_fees')
    ->select('stopdesk', 'domicile')
    ->where('destination', 'like', "%{$this->wil}%")
    ->get();

补充说明

  • 确保Livewire组件中正确声明$wil属性,并监听选择变化自动查询:
    class YourComponent extends Component
    {
        public $wil;
        public $fees;
    
        public function updatedWil()
        {
            // 用户选择变化时自动更新费用数据
            $this->fees = $this->wil 
                ? DB::table('delivery_fees')
                    ->select('stopdesk', 'domicile')
                    ->where('destination', $this->wil)
                    ->first()
                : null;
        }
    
        // ... 其他组件代码
    }
    
  • 用first()代替get()更合理,因为每个目的地应对应唯一的费用记录,first()直接返回单条数据,便于视图直接调用字段值。

内容的提问来源于stack exchange,提问作者MOHAMED KESSOUM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:12:11