简体   繁体   中英

How to get data with hasMany relation and hasMany in laravel?

I have Two table (projects, tasks).

projects table structure looks like this:

id - title - desc - others_column
1  - title - desc - others
2  - title - desc - others

tasks table structure looks like this:

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

I have tried to query, Project Controller looks like this.

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();   
   }
}

And Project Model Look like this:

use Illuminate\Database\Eloquent\Model; 
class Project extends Model { 
    public function tasks() {
        return $this->hasMany('App\Task');
    }
} 

I'm getting result looks like this:

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

But I wanna get results looks like this:

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

Now any one can help me to get the proper results.

Thanks

Use this subtasks relationship:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM