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

使用AdonisJS创建自关联子分类返回[]/null,求解决方案

解决AdonisJS自关联子分类返回空的问题

你的代码存在几个关键问题,导致预加载的子分类返回空数组或null,以下是具体修复方案:

1. 修正模型的关联配置

@hasMany 自关联时必须明确指定外键与本地键,否则AdonisJS默认的关联规则会与你的数据库结构不匹配。修改模型代码如下:

import { column, hasMany, HasMany } from '@adonisjs/lucid/orm'
import Model from './BaseModel' // 替换为你的实际基础模型路径

export default class Category extends Model {
  @column({ isPrimary: true })
  public id: bigint

  @column()
  public categoryId: bigint | null

  @hasMany(() => Category, {
    foreignKey: 'categoryId', // 子表中关联父表的字段
    localKey: 'id', // 父表的主键字段
  })
  public subCategory: HasMany<typeof Category>
}

2. 统一字段类型

迁移文件中category_id是bigInteger类型,但你模型里定义的categoryId是string,类型不匹配会导致关联查询无法匹配数据,必须将模型字段类型改为bigint(对应数据库的bigInteger)。

3. 检查数据库数据

确认数据库中存在category_id不为null的子分类数据,且这些category_id确实对应已存在的父分类id。比如父分类id为1,子分类的category_id需设置为1,才能被预加载关联上。

4. 调试查询逻辑

可以在预加载时开启调试,查看实际执行的SQL语句,确认查询逻辑是否正确:

const categories = await Category.query()
  .whereNull('category_id')
  .preload('subCategory', (query) => {
    query.debug() // 开启调试,打印执行的SQL
  })
  .paginate(page, limit)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:25:37