[英]How to get data with hasMany relation and hasMany in laravel?
我有兩個表(項目,任務)。
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": [ ]
}
] },
現在任何人都可以幫助我獲得正確的結果。
謝謝
使用此subtasks
關系:
class Task extends Model {
public function subtasks() {
return $this->hasMany(self::class, 'parent_id')->with('subtasks');
}
}
$projects = Project::with('tasks.subtasks')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.