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

Laravel拼接两列字段报错:列未找到,请求排查解决

问题分析与修复

你的查询报错“列未找到”,核心是三个问题导致的:

  • 链式调用顺序错误:pluck()方法会直接执行查询并返回键值对集合,不能在它之后再调用join()或get()——这会导致框架试图在已返回的集合上执行数据库操作,自然找不到对应列。
  • DB::raw参数冗余:你给DB::raw()传了两个参数,第二个'recepcion_cargo.id'是无效的,DB::raw()只需要传入SQL表达式字符串。
  • 不必要的字段查询:如果最终只需要拼接后的TOTAL和对应ID,不需要查询其他无关字段,徒增数据库开销。

修正后的代码

场景1:rcargo_id为空时

public function obtenerCargo() {
    if ($this->rcargo_id == null) {
        $this->listCargo = recepcionCargo::select(
            'recepcion_cargo.id',
            DB::raw("CONCAT(recepcion_cargo.total, ' ', recepcion_cargo.total_sp) AS TOTAL")
        )
        ->join('cargo_id', 'cargo_id.id', '=', 'recepcion_cargo.car_id')
        ->pluck('TOTAL', 'recepcion_cargo.id');
    } else {
        // 场景2代码
    }
}

场景2:rcargo_id不为空时

public function obtenerCargo() {
    if ($this->rcargo_id == null) {
        // 场景1代码
    } else {
        $this->listCargo = recepcionCargo::select(
            'recepcion_cargo.rcargo_id',
            DB::raw("CONCAT(recepcion_cargo.total, ' ', recepcion_cargo.total_sp) AS TOTAL")
        )
        ->join('cargo_id', 'cargo_id.id', '=', 'recepcion_cargo.car_id')
        ->where('recepcion_cargo.rcargo_id', '=', $this->rcargo_id)
        ->pluck('TOTAL', 'recepcion_cargo.rcargo_id');
    }
}

视图表格展示的补充优化

如果你的视图需要展示完整表格(不止拼接的TOTAL),pluck()就不适用了(它只返回键值对)。这种情况下应该保留所需字段,用get()获取完整集合:

public function obtenerCargo() {
    $query = recepcionCargo::select(
        'recepcion_cargo.id',
        'recepcion_cargo.rcargo_id',
        'recepcion_cargo.no_factura',
        'cargo_id.cargo_id',
        'recepcion_cargo.porcentaje',
        // 保留你需要的其他业务字段
        DB::raw("CONCAT(recepcion_cargo.total, ' ', recepcion_cargo.total_sp) AS TOTAL")
    )->join('cargo_id', 'cargo_id.id', '=', 'recepcion_cargo.car_id');

    if ($this->rcargo_id != null) {
        $query->where('recepcion_cargo.rcargo_id', '=', $this->rcargo_id);
    }

    $this->listCargo = $query->get();
}

之后在视图里遍历listCargo,直接用$item->TOTAL展示拼接字段,隐藏原始的total和total_sp即可。

内容的提问来源于stack exchange,提问作者Brayan Galvan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:03:17