jenoh
jenoh

Reputation: 179

Eloquent eager loading with hasMany relation doesn't work

My code currently doesn't work, but my relations are correct.

Project model

public function timeEntries()
{
    return $this->hasMany('App\Model\TimeEntries');
}

$array_of_project = Project::with('timeEntries')
    ->whereBetween('spent_on', [($request->debut)), ($request->fin))])
    ->get();

It doesn't find 'spent_on.'

Upvotes: 0

Views: 572

Answers (3)

vanjamlin
vanjamlin

Reputation: 386

It looks like you are trying to constrain the relation's records. I suggest looking at the documentation for constraining eager loading. Here is a code sample of what I think you are trying to accomplish:

$projects = App\Model\Project::with(['timeEntries' => function ($query) use ($request) {
    $query->whereBetween('spent_on', $request->debut, $request->fin);
}])->get();

https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads

Upvotes: 1

Thomas
Thomas

Reputation: 8859

If spent_on is a column in the time_entries table then your whereBetween is not correct since it will look inside the projects table. But you can add it to with instead:

$array_of_project = Project::with(['timeEntries' => function($query) use ($request) {
    return $query->whereBetween('spent_on', [$request->input('debut'), $request->input('fin')]);
})->get();

Upvotes: 0

IGP
IGP

Reputation: 15879

Like @aynber wrote, if your spent_on attribute is part of the related model, it should be included in the query with a closure.

$array_of_project = Project::with(['timeEntries' => function ($time_entry) use ($request) {
    $time_entry->whereBetween('spent_on', [$request->input('debut'), $request->input('fin')]);
}])->get();

Upvotes: 0

Related Questions