php - 如何在 laravel 中使用 hasMany 关系和 hasMany 获取数据?
问题描述
我有两个表(项目,任务)。
项目表结构如下所示:
id - title - desc - others_column
1 - title - desc - others
2 - title - desc - others
任务表结构如下所示:
id - title - desc - project_id - parent_id - others_column
1 - title - desc - 1 - null - others
2 - title - desc - 1 - 1 - others
3 - title - desc - 2 - null - others
4 - title - desc - 2 - 3 - others
我试过查询,项目控制器是这样的。
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Project;
use App\Task;
class ProjectsController extends Controller {
public function index(Request $request) {
$projects = new Project;
$projects = $projects->with('tasks');
$projects = $projects->get();
}
}
和项目模型看起来像这样:
use Illuminate\Database\Eloquent\Model;
class Project extends Model {
public function tasks() {
return $this->hasMany('App\Task');
}
}
我得到的结果如下所示:
{
"id":1,
"title":"title",
"desc":"desc",
"tasks":[
{
"id":1,
"title":"Title",
"desc":"Desc",
"todo_project_id":1,
"parent_id":null,
}
{
"id":2,
"title":"Title",
"desc":"Desc",
"todo_project_id":1,
"parent_id": 1,
}
] },
但我想得到这样的结果:
{
"id":1,
"title":"title",
"desc":"desc",
"tasks":[
{
"id":1,
"title":"Title",
"desc":"Desc",
"todo_project_id":1,
"parent_id":null,
"subtasks": [
{
"id":2,
"title":"Title",
"desc":"Desc",
"todo_project_id":1,
"parent_id": 1,
},
{
"id":3,
"title":"Title",
"desc":"Desc",
"todo_project_id":1,
"parent_id": 1,
},
]
},
{
"id":4,
"title":"Title",
"desc":"Desc",
"todo_project_id":2,
"parent_id":null,
"subtasks": [ ]
}
] },
现在任何人都可以帮助我得到正确的结果。
谢谢
解决方案
使用这种subtasks
关系:
class Task extends Model {
public function subtasks() {
return $this->hasMany(self::class, 'parent_id')->with('subtasks');
}
}
$projects = Project::with('tasks.subtasks')->get();
推荐阅读
- javascript - 加载时修改模式窗口中的数据
- python - 将 args 和 kwargs 规范化为 kwarg 规范形式
- vba - 如何对过滤后的 ListBox 进行排序
- c++ - X3 和 MS VS2017 的问题
- git - Git rebase 的 --merge 选项有什么作用?
- android - Android Emulator 无法绑定到本地 8601、8600 进行调试
- python - 当 .dropna() 使它们的大小不同时,处理两个数据集的正确方法是什么?
- pytorch - 手动修改 pytorch state_dict 文件并重新训练
- python - 检查包是否从源代码树中导入
- gateway - Kong Cloud 是否支持自定义插件?