在类别表3个字段中
id categoryName parent_id
1 Architect 0
2 Vendor 0
3 Res Architect 1
4 Electrician 2
在我的模型中
public function parent()
{
return $this->belongsTo(Category::class, 'id');
}
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
在控制器中
SELECT t2.categoryName FROM categories t1, categories t2
WHERE t1.id = id
AND t2.parent_id = t1.id
我不知道要通过自我连接来获取记录到laravel中的一个表中 请帮助
答案 0 :(得分:1)
您必须稍微修改父级关系,它应该是parent_id
,因为子级通过使用parent_id
字段来引用父级。
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
您可以这样做
获取带有其子级的所有父级
$parentCategories = Category::with('children')->where('parent_id', 0)->get();
让所有孩子和父母同住
$childCategories = Category::with('parent')->where('parent_id','>', 0)->get();
现在这样获取
foreach($parentCategories as $parentCategory){
dd($parentCategory->children); //children for parent category
}
类似地针对子类别
foreach($childCategories as $childCategory){
dd($childCategory->parent); //parent of child category
}
获取电工(根据您的评论要求)
$electrician = Category::with('parent')->where('id', 4)->first();
dd($electrician->parent); //this will be Vendor
OR (如果要获取供应商的所有子代,则
$vendor = Category::with('children')->where('id', 2)->first();
dd($vendor->children); //children of vendor