I believe what your looking for is the Has Many Through Relationship.
Nested Method Eager Loading
I have a model that looks like this.
public function assessment()
{
return $this->question->assessment()->withTrashed();
}
public function question()
{
return $this->belongsTo("App\Models\AssessmentQuestion", 'question_id')->withTrashed();
}
and I was wondering why this works
$this->load('question', 'question.assessment');
info($this->question->assessment);
but this does not
$this->load('question', 'assessment');
info($this->assessment);
Or if there is just a better way to do this?
Thanks! -Alex
@PavanKataria I love the way you answered that :) However, you didn't really answer the question, since the OP does define that as a relation (technically valid relation).
@slaughter550 First, let me say, that your code works, but obviously doesn't do what you expect it to. Next thing - hasManyThrough wouldn't work here, since it is belongsTo (and I assume the same for question-assessment relation).
Now, the reason that your pseudo-relation can't be used while eager loading, is because of the way eager loading works internally, as opposed to loading something on the instance:
$model->assessment; // gets everything forom the instances' attributes
$model->load('assessment'); // gets everything from the queried collections
It means that the latter gets a collection of related models, then runs another query for each nested relation with a where id in (...) clause. in your case there is no id for the where in part, since you have no assessment_id on your $model.
Eventually your code really worked and queried assessments table, but with a where id in (0) clause, that's why you get no results.
Like already mentioned by @pmall - such relation is not gonna work the eloquent way, so I suggest you don't use it as one. You can do this instead:
// accessor immitating relation's dynamic property:
public function getAssessmentAttribute()
{
return ($this->question) ? $this->question->assessment : null;
}
// then
$model->load('question.assessment');
$model->assessment;
Finally, read this http://softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/
Please or to participate in this conversation.