I'm trying to get the title of a job belonging to a task. When i try to get the title I get a N 1 popup from my laravel debugbar. This instructs me to use with but whichever way I have tried (using with('App/Models/Job') or just with('job') or setting protected $with = ['job'] etc) I still get the N 1 popup. So heres the applicable code App/Models/Job.php
public function tasks()
{
return $this->hasMany( Task::class);
}
App/Models/Task.php
public function job()
{
return $this->belongsTo( Job::class);
}
App/Models/Planner.php
public static function getTask($user, $date)
{
return Task::where( 'user_id', $user->id )
->where('date', $day)
->with('job')
->get();
App/Http/Controllers/PlannerController.php
public function index( Request $request )
{
return View::make( 'pages.planner.index' )
->with( 'task', Planner::getTask( 1, '2022-26-05' ) );
}
and finally in resources/views/pages/planner/index.blade.php
<div>
<div>{{ $task->job->title }}</div>
</div>
The task references the 'number' field in job via it's 'job_number' field and job doesn't contain any reference to task (as a job can have many tasks)
So how do I get the title of a tasks job without getting the N 1 error?
thanks
** EDIT ** Following suggestions by WebPajooh. I have modified the above code to remove the parenthesis in my blade file and removed all() from the relationship.
I still get a N 1 error:
Found the following N 1 queries in this request:
Model: App\Models\Task => Relation: App\Models\Job - You should add "with('App\Models\Job')" to eager-load this relation.
CodePudding user response:
When you write job()
, it returns a relationship but when you write job
without parentheses, it doesn't call the relationship.
Note: You don't need to call all()
after get()
, because get()
returns a collection.
CodePudding user response:
Following on from suggestions by WebPajooh I found that adding protected $with = ['job'];
to my Task model allowed my code to work without this issue.