php - Getting the results of a query, depending on results of first query

I have 2 tables. 1 named tasks that has the rows [id, event_id, title] and the other table is named task_items with the rows [id, task_id, description, ...].

I am trying to run a query to retrieve all tasks with an event_id of x, then all task_items that match the id of any result from the previous query. I currently have 2 standalone queries, but don't know how to join them to work in-tandem. The current code that I have show all task_items associated with the event, but they aren't corresponding with each task. Task 0 in my database has 0 task_items, but my code is displaying the task_items for task 0 under task 1.

This is my query code:

$tasks = DB::table('tasks')->where('event_id', $request->route('id'))->get();
    foreach($tasks as $task)
    {
        $taskItemID[] = $task->id;
    }
    $taskItems = DB::table('task_items')->whereIn('task_id', $taskItemID)->get();

This is my foreach loop:

@foreach($tasks as $task)
                    <div><b>Task # {{$task->id}}:</b> {{$task->title}}</div>
                    <div style="float:right;">mark as completed</div>
                  </div>
                  <div class="row" style="border: 1px solid #efefef;padding: 20px;">
                    @foreach($taskItems as $taskItem)
                      <li>{{$taskItem->description}}</li>
                    @endforeach
                      @endforeach

Answer

Solution:

I had to tweak @Kamlesh Paul's code a bit, but this worked for me:

$tasksData = DB::table('tasks')->where('event_id', $request->route('id'))->get();
    foreach ($tasksData as $task) {
          $temp = $task;
          $temp->task_items = DB::table('task_items')->where('task_id', $task->id)->get();
          $tasks[] = $temp;
    }

Answer

Solution:

As you don't want to use Model then

try somthing like this to create new child data

$tasksData = DB::table('tasks')->where('event_id', $request->route('id'))->get();
    $tasks = collect();
    foreach ($tasksData as $task) {
          $temp = $task;
          $temp->task_items = DB::table('task_items')->where('task_id', $task->id)->get();
          $data[] = $temp;
    }
return $tasks;

then you can get $tasks with all the $task_items to get all task_item you can $tasks[0]->task_items

you can use in your blade like this

@foreach($tasks as $task)
<div><b>Task # {{$task->id}}:</b> {{$task->title}}</div>
<div style="float:right;">mark as completed</div>
</div>
<div class="row" style="border: 1px solid #efefef;padding: 20px;">
    @foreach($task->task_items as $taskItem)
    <li>{{$taskItem->description}}</li>
    @endforeach
@endforeach

NOTE i am not recommend this but at in your can you can use this

Source