Is it right that you use count() on a model (returned by first()) and not on a collection?
Maybe this would give you proper result?
$level->readableLessons->first()->progresses->count()
Am I doing something wrong, or does loading a subrelation ignore the filter?
$level->load([
"readableLessons.progresses" => function ($query) {
$query->where("state", "completed");
},
]);
When I count the items in $level->readableLessons->first()->progresses->first()->count(), I get the wrong number, because it isn't filtering out only the ones that are completed.
Any comments please?
Thank you everyone for your ideas. I found out what I was doing wrong. It turns out my code as originally posted would have worked correctly, but that's not exactly what I was doing. I was also calling "load" a second time to load another relation "readableLessons.translations". It turns out if I call "load" twice, the second call somehow deletes the first one. The following code doesn't work.
$level->load("readableLessons");
$level->load([
"readableLessons.progresses" => function ($query) {
$query->where("user_id", Auth::id())->where("state", "completed");
},
]);
$level->load([
"readableLessons.translations" => function ($query) {
$query->where("language_id", session("languageId", "en_CA"));
},
]);
This code does work:
$level->load([
"readableLessons",
"readableLessons.progresses" => function ($query) {
$query->where("user_id", Auth::id())->where("state", "completed");
},
"readableLessons.translations" => function ($query) {
$query->where("language_id", session("languageId", "en_CA"));
},
]);
I'm no expert, but I might be tempted to consider this a bug. At the least it's not expected.
Please or to participate in this conversation.