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

Laravel同模型多对多关联字符串主键下pn值显示为0问题求解

问题根因为Laravel默认模型主键为自增整数类型,未手动配置的情况下会自动将主键值强制转换为整数,字符串A1转换为整数后结果为0,导致主键查询、关联匹配时全部使用错误的0值进行匹配,才会出现字段返回0、关联返回全部记录的异常。

修复步骤

1. 修正Pn模型的主键配置

在Pn模型中添加三个属性,覆盖默认的整数主键配置即可,原有关联定义不需要修改:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Pn extends Model
{
    // 明确指定主键字段为pn
    protected $primaryKey = 'pn';
    // 关闭主键自增特性
    public $incrementing = false;
    // 指定主键类型为字符串
    protected $keyType = 'string';

    // 原有BOM关联保持不变
    public function bom()
    {
        return $this->belongsToMany(Pn::class, 'boms', 'parent_pn', 'child_pn');
    }

    // 原有父件查询关联保持不变
    public function where_used()
    {
        return $this->belongsToMany(Pn::class, 'boms', 'child_pn', 'parent_pn');
    }
}

2. 确认中间表字段类型匹配

检查BOM中间表的迁移定义,确保parent_pn、child_pn两个字段的类型、长度和pn表的pn字段完全一致,示例如下:

Schema::create('boms', function (Blueprint $table) {
    // 字段类型和长度必须和pns表的pn字段完全一致
    $table->string('parent_pn', 50);
    $table->string('child_pn', 50);
    // 设置联合主键避免重复的关联关系
    $table->primary(['parent_pn', 'child_pn']);

    // 可选:添加外键约束保证数据一致性
    $table->foreign('parent_pn')->references('pn')->on('pns')->cascadeOnDelete();
    $table->foreign('child_pn')->references('pn')->on('pns')->cascadeOnDelete();
});

3. 验证查询结果

配置完成后清理Laravel缓存避免旧配置生效:
php artisan cache:clear && php artisan config:clear

再执行查询即可得到正确结果:

// 查询A1的物料及关联的子件、父件
$pn = Pn::with(['bom', 'where_used'])->find('A1');
// $pn->pn 会正确返回字符串A1,bom和where_used仅返回匹配的关联记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:45:03