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
相关产品推荐
相关产品推荐

