The Setup And Dummy Data
I have a simple model called Category, which has the following schema:
|----------------------------------------------|
| cat_id | cat_name | parent_id |
|----------------------------------------------|
| 1 | Home | 0 |
|----------------------------------------------|
| 2 | Products | 1 |
|----------------------------------------------|
| 3 | Services | 1 |
|----------------------------------------------|
| 4 | Product A | 2 |
|----------------------------------------------|
| 5 | Product B | 2 |
|----------------------------------------------|
期望的输出
So you can see that we would get a very straight forward hierarchy as follows:
Home
- Products
- Product A
- Product B
- Services
这个问题
我试图在Laravel 4.2中映射这种关系,这样我就可以查询一个模型并获取它的父类(它总是有父类)和子类(如果它们存在的话).
I've defined the relationship in the Category model using:
public function children()
{
return $this->hasMany('Category', 'parent_id', 'cat_id');
}
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
The Problem
我可以使用
$category = Category::findOrFail($id);
return $category->parent->cat_name;
However, I don't understand how to get the child objects.
我试过:
$category = Category::findOrFail($id);
$children = $category->children();
但是当我dd($Children)时,它没有输出我期望的结果.