我有两个模型,它们彼此相关,具有belongsToMany
关系。模型Game
和Category
.当然,两者的表都是games
和categories
。Category
模型有自己的父子关系。
基本上这是我的"简化"结构:
Table game:
id unsigned integer
name string
Table categories:
id unsigned integer
name string
parent_id unsigned integer nullable
当类别没有父级时,parent_id
列null
,但如果它是某个其他类别的子级,则它具有引用同一表中行的现有 id。
Table category_game
category_id unsigned integer
game_id unsigned integer
category_id
列,引用id
categories
表。它应仅引用游戏所属的顶级类别。游戏可以属于许多不同的类别,但在数据透视表中,应该只引用父类别。例如,如果我有这样的类别结构:
Category 1
Category 2
Category 4
Category 3
Category 9
Category 5
Category 6
Category 7
Category 8
我想为我的游戏 1 和 2 提供以下信息:
category_id game_id
3 1
5 1
1 2
这应该意味着我的游戏 1 有类别:3、9、5、6、7 和 8。 而我的游戏 2 有类别:1、2、4、3 和 9
我知道我的Laravel模型应该有这个:
class Game {
public function categories(){
return $this->belongsToMany( Category::class );
}
}
class Category{
public function games(){
return $this->belongsToMany( Game::class );
}
}
但是我不知道如何使用Eloquent检索子类别。我知道belongsToMany
方法有更多参数可能有助于解决我的问题,但我不知道如何使用它们。
模型类别桌category_game
游戏
class CategoryGame{
public function childCategories() {
return $this->hasMany(Category::class, 'parent_id','category_id');
}
}
您可以访问
$games = AppCategoryGame::all();
foreach ($games as $game ) {
foreach ($game->childCategories as $category) {
echo $category->name;
}
}
如果不起作用,请告诉我
扩展模型:
class Category {
public function children() {
return $this->hasMany(Category::class, 'parent_id');
}
}
class Game {
public function getAllCategoriesAttribute() {
$result = collect();
$children = function($categories) use(&$result, &$children) {
if($categories->isEmpty()) return;
$result = $result->merge($categories);
$children($categories->pluck('children')->collapse());
};
$children($this->categories);
return $result;
}
}
然后,您可以像这样访问类别:
Game::find($id)->allCategories;