我有 2 个模型,用户和部门。这两者之间有着多对多的关系。当我尝试在 Model 类中将字段与toArray()方法相关联时,出现最大堆栈深度超出错误。
部门型号 :
class Department extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function toArray()
{
$arr = parent::toArray();
$arr['users'] = $this->users;
return $arr;
}
}
用户模型:
class User extends Model
{
public function departments()
{
return $this->belongsToMany(Department::class);
}
public function toArray()
{
$arr = parent::toArray();
$arr['departments'] = $this->departments;
return $arr;
}
}
拥有这种 JSON 输出的正确方法是什么?
/api/部门:
{
"success": true,
"data": [
{
"id": 1,
"caption": "asd",
"status": "active",
"users": []
}
]
}
/api/用户:
{
"success": true,
"data": [
{
"id": 1,
"username": "asdasd",
"email": "m@m.m",
"status": "active",
"departments": []
}
]
}
慕容708150
互换的青春