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

Laravel 5中Game与Category的belongsToMany关联及分类父子关系问题

Game与Category模型的关联及实现指南

我来帮你把这两个模型的关联逻辑、数据表结构以及对应的Eloquent实现梳理清楚,方便你在Laravel里使用:

核心关联关系

首先明确:Game和Category是**多对多(belongsToMany)**关系,这意味着一个游戏可以属于多个分类,一个分类也可以包含多个游戏。这种关系需要一个中间表来维护双方的关联记录。

完整数据表结构

除了你提到的games和categories表,还需要一个中间表(默认命名为game_category,可自定义):

games表

字段名数据类型说明
id无符号整数主键,自增
name字符串游戏名称,建议设置长度(如varchar(255))

categories表

字段名数据类型说明
id无符号整数主键,自增
name字符串分类名称
parent_id可为空的无符号整数父分类ID,无父级时设为null

中间表 game_category(必填)

字段名数据类型说明
game_id无符号整数关联games表的id字段
category_id无符号整数关联categories表的id字段

提示:建议给这个中间表的game_id和category_id设置联合主键,避免重复关联记录。

Eloquent模型实现

下面是两个模型的代码示例,包含多对多关联和分类的父子递归关联:

Game 模型

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Game extends Model
{
    // 如果表名不是默认的复数形式,需要指定
    protected $table = 'games';

    // 定义与分类的多对多关联
    public function categories(): BelongsToMany
    {
        // 如果中间表或字段不是默认值,需要额外参数:
        // return $this->belongsToMany(Category::class, '自定义中间表名', '游戏侧外键', '分类侧外键');
        return $this->belongsToMany(Category::class);
    }
}

Category 模型

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Category extends Model
{
    protected $table = 'categories';

    // 定义与游戏的多对多关联
    public function games(): BelongsToMany
    {
        return $this->belongsToMany(Game::class);
    }

    // 关联父分类(一对多反向关联)
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    // 关联直接子分类(一对多关联)
    public function children(): HasMany
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    // 可选:递归获取所有层级的子分类(含子分类的子分类)
    public function allChildren(): HasMany
    {
        return $this->children()->with('allChildren');
    }
}

使用示例

  • 获取某个游戏的所有分类:$game->categories
  • 获取某个分类下的所有游戏:$category->games
  • 获取某个分类的父分类:$category->parent
  • 获取某个分类的直接子分类:$category->children
  • 获取某个分类的所有层级子分类:$category->allChildren

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:34:09