php - 如何使用 hasMany 关系和 laravel 中的 hasMany 获取数据?

标签 php laravel-5 relation

我有两个表(项目、任务)。

项目表结构如下:

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

我去查询了一下,Project Controller长这样

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": [ ]
     }
  ] }, 

现在任何人都可以帮助我获得正确的结果。

谢谢

最佳答案

使用此子任务关系:

class Task extends Model { 
    public function subtasks() {
        return $this->hasMany(self::class, 'parent_id')->with('subtasks');
    }
}

$projects = Project::with('tasks.subtasks')->get();

关于php - 如何使用 hasMany 关系和 laravel 中的 hasMany 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685272/

相关文章:

r - R中代数关系的笛卡尔积表

php - Google API PHP 客户端 - 通讯录服务

javascript - Laravel Elixir 使用 Typescript 而不是 Javascript

Laravel 5.2 Eloquent 地返回软删除记录

node.js - Loopback v3关系用户模型及其他模型结构

sql - Laravel eloquent where with 关系

php - 从子数组 mongo 文档中删除元素

php - 在 VIM for PHP 中自动格式化

php - 随机数、列和行。 PHP

Laravel:插入数据透视表