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

Laravel中PostgreSQL返回ticket_number为id显示0的问题排查

Laravel中别名id字段返回0的解决方案

问题原因

你的LeadsTickets模型默认主键为数据库表的id,Laravel Eloquent在处理查询结果时,会优先将模型主键对应的数据库字段值赋值给模型的id属性。当你通过selectRaw将ticket_number别名成id时:

  1. Eloquent会自动把数据库原id字段(数值类型)赋值给模型id属性
  2. 即使查询返回了别名的id(字符串类型,如TK33412),Laravel会尝试将其转换为模型主键的类型(通常是int),转换失败后就会显示为0。

而使用其他别名(如ids)时,因为不是模型的主键字段,Eloquent不会做特殊处理,所以能正常返回字符串值。

解决方法

方法1:临时修改模型主键

在查询前临时修改模型的主键字段,让Eloquent不再使用原id作为主键,避免覆盖你别名的id:

// 实例化模型并保存原主键名称
$ticketModel = new \App\Models\DM\LeadsTickets();
$originalPrimaryKey = $ticketModel->getKeyName();

// 临时将主键设置为ticket_number(或不存在的字段)
$ticketModel->setKeyName('ticket_number');

// 执行查询
$mainSelect = "CAST(ticket_number as varchar) as id";
$query = $ticketModel->selectRaw($mainSelect);
$queryResponse = $query->paginate($perPage, $page);

// 恢复原主键,避免影响后续操作
$ticketModel->setKeyName($originalPrimaryKey);

return $queryResponse;

方法2:分页后手动修改集合

先查询时用其他别名获取ticket_number,再遍历分页集合替换id值:

// 用临时别名获取ticket_number,同时保留原id(可选)
$mainSelect = "CAST(ticket_number as varchar) as ticket_id, id as original_id";
$query = \App\Models\DM\LeadsTickets::selectRaw($mainSelect);
$queryResponse = $query->paginate($perPage, $page);

// 遍历集合替换id字段
$queryResponse->getCollection()->transform(function ($item) {
    $item->id = $item->ticket_id;
    // 移除临时字段
    unset($item->ticket_id, $item->original_id);
    return $item;
});

return $queryResponse;

方法3:直接使用DB门面查询

绕开Eloquent模型的主键处理逻辑,直接用查询构建器操作:

$mainSelect = "CAST(ticket_number as varchar) as id";
$queryResponse = \DB::table('tickets')
    ->selectRaw($mainSelect)
    ->paginate($perPage, $page);

return $queryResponse;

内容的提问来源于stack exchange,提问作者Punit Gajjar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:30:43