我有三个桌子。结构是:
1. categories
id - integer
name - string
2. sub_Categories
id - integer
category_id - integer
name - string
3. sub_catergory_threes
id - integer
sub_Category_id - integer
name- string
现在,我想显示三个级别的类别,如“类别”,以及将鼠标悬停在任何类别项目上时,将显示该类别的子类别,以及将鼠标悬停在任何SubCategory项目上时,将显示该子类别的Sub_Categories_Three
我使用laravel雄辩,这是我的模型
类别模型
public function subcategories(){
return $this->hasMany('App\SubCategory');
}
子类别模型
public function subcategoriesthree(){
return $this->hasMany('App\SubCategoryThree');
}
public function category(){
return $this->belongsTo('App\Category');
}
SubCategoriesThree模型
public function subcategory(){
return $this->belongsTo('App\SubCategory');
}
答案 0 :(得分:1)
您可以使用ELoquent关系来加载所有相关数据
$categories = App\Category::with('subcategories.subcategoriesthree')->get();
这将加载所有类别及其子类别和子类别
如果需要动态加载,则可以在控制器中使用
public function loadSubCategory($categoryId)
{
$category = App\Category::findOrFail($categoryId);
$subcategories = $category->subcategories()->get();
return $subcategories;
}
public function loadSubSubCategory($subcategoryId)
{
$subcategory = App\SubCategory::findOrFail($subcategoryId);
$subsubcategories = $subcategory->subcategoriesthree()->get();
return $subsubcategories;
}
答案 1 :(得分:1)
因此您可以像这样编辑模型:
子类别
public function subcategoriesthree(){
return $this->hasMany('App\SubCategoryThree');
}
public function category(){
return $this->belongsTo('App\Category', 'category_id');
}
SubCategoriesThree
public function subcategory(){
return $this->belongsTo('App\SubCategory', 'sub_Category_id');
}
在您的控制器中:
$categories = Category::with(['subcategories', 'subcategories.subcategoriesthree'])->get();
然后您可以dd($categories)
并在subcategories
下看到subcategoriesthree
。