请教 Laravel Eloquent 模型关联嵌套扁平化
第一次发帖,有不对之处请指正!我有这样的模型关系:
class Member extends Model{
public function parent()
{
return $this->belongsTo(self::class, 'pid', 'id');
}
public function ancestors()
{
return $this->parent()->with('ancestors');
}
}
我在控制器这样定义的:
use App\Models\Member;
class MembersController extends Controller
{
public function membAncestor($id)
{
$member = Member::with('ancestors')->find($id);
return $member;
}
}
然后得到这样的结果:
[
{
"id": 107,
"name": 'Parent',
"pid": 104,
'ancestors': [
{
"id": 104,
"name": 'Parent1',
"pid": 56,
'ancestors': [
{
"id": 56,
"name": 'Parent2',
"pid": 55,
'ancestors': [
{
"id": 55,
"name": 'Parent3',
"pid": 38,
'ancestors': [
{
"id": 38,
"name": 'Parent4',
"pid": 35,
'ancestors': null
}
]
}
]
}
]
}
]
}
]
而我想要得到结果是这样的:
[
{
"id": 107,
"name": 'Parent',
"pid": 104,
},
{
"id": 104,
"name": 'Parent1',
"pid": 56,
},
{
"id": 56,
"name": 'Parent2',
"pid": 55,
},
{
"id": 55,
"name": 'Parent3',
"pid": 38,
},
{
"id": 38,
"name": 'Parent4',
"pid": 35,
}
]
推荐文章: