Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sulieman's avatar

tasks morphs to project or to milestone

hi, i have 3 tables: projects milestones task

the project have many milestones the milestone morphMany tasks the project morphMany tasks

how to get all the tasks that belong to project or belong to milestone that belong to that project ?

0 likes
4 replies
otepas's avatar

@Sulieman, I am not great with DB queries, so I tend to follow a trial & error process until I get what I need. I usually start with the separate pieces that I need and when everything works on its own I try to get a single query. This is where I would start:

Assuming that Task has the properties taskable_type and taskable_id:

$projectTasks = Task::where('taskable_type', 'Project')
    ->where('taskable_id', $project->id)
    ->get();

$milestoneTasks = Task::join('milestones', 'tasks.taskable_id', '=', 'milestones.id')
    ->where('taskable_type', 'Milestone')
    ->where('milestones.project_id', $project->id)
    ->get();

Hope this helps.

Sulieman's avatar

yes your code work, my way also work :

$project_tasks = Project::find(1)->tasks();

$project_milestones =  Project::find(1)->milestones();

foreach ($project_milestones->tasks as $task)
{
    $milestones_tasks[] = $task
}

i want a way to make it with one query

otepas's avatar
otepas
Best Answer
Level 13

Well, now you "just" have to merge the 2 queries. Try with something like this:

$tasks = Task::join('milestones', 'tasks.taskable_id', '=', 'milestones.id')
    ->where(function ($query) {
        $query->where('taskable_type', 'Project')
            ->where('taskable_id', $project->id)
        })
    ->orWhere(function ($query) {
        $query->where('taskable_type', 'Milestone')
            ->where('milestones.project_id', $project->id);
    })
    ->get();

Please or to participate in this conversation.