Reputation: 505
I have a problem with a query. I have 3 models: Course,MainTask and Task. Course has many MainTasks and a MainTask has many Tasks.
I have the users current MainTask stored in the database, i want to select the Course with the main task and tasks where the users current main task and course is.
My attempt:
$tasks=Course::where('id',$current->current_course)->whereHas('mainTask', function ($q) use ($current)
{
$q->where('id',$current->current_main_task_id);
})->with('mainTask.task')->first();
But this returns all the main tasks not just 1.
class Course extends Model
{
public function mainTask () {
return $this->hasMany('App\MainTask');
}
}
class MainTask extends Model
{
use SoftDeletes;
public function task () {
return $this->hasMany('App\Task');
}
public function course () {
return $this->belongsTo('Courses');
}
}
class Task extends Model
{
use SoftDeletes;
public function mainTask () {
return $this->belongsTo('MainTask');
}
}
Any tips?
Thanks
Upvotes: 2
Views: 41
Reputation: 505
$tasks=Course::where('id',$current->current_course)
->with(['mainTask' => function ($q) use ($current)
{
return $q->where('id',$current->current_main_task_id);
},'mainTask.task'])->first();
Upvotes: 0
Reputation: 6335
Looks like loading the relationships from your mainTask would be easiest:
MainTask::with('course', 'task')->find($current->current_main_task_id);
Will load 1 main task with it's course and all of it's tasks
Upvotes: 1