‘Disable’ $appends when calling a collection
Hi all, I am currently having an issue involving relationship eager loading and custom attribute appending. As example let’s say I have many schools, that have many pupils, with many comments
( that are collected in a certain way- a custom collection) When I load a single school, I want my custom attribute to be readily available via $appends
because it goes into a vue component. I should be able to get it by this $school->pupils->first()->threaded_comment
. This works when I add it to protected $appends
in the pupils model. Unfortunately when I load all my Schools on an index page, the comments are also loaded, making the database create *138** queries. When I turn off appends only 40 queries are made. How can stop the attribute from being loaded when I get a collection?
Class School extends Model {
Public function pupils(){
Return $this->hasMany(‘AppPupil’)
}
}
Class Pupil extends Model {
Protected $appends = [‘threaded_comments’];
Public function commetns(){
Return $this->hasMany(‘AppComment')
}
Public function getThreadedCommentsAttribute(){
If(!isset($this->relation[‘comments’]){
$this->load(‘comments’);
}
Return $this->relation[‘comments’]->threaded();
}
}
*Threaded is the my custom collection (thanks Laracasts). I have tried the following:
1. Changed the threaded attribute method to the below
Public function getThreadedCommentsAttribute(){
If(relationshipLoaded(‘comments’)){
Return $this->relation[‘comments’]->threaded();
}
}
Then I hoped to control the appearance of the attribute by whether I manually eager load commnets or not School::with(‘pupils.comments’)
. this still doesn’t work. (Are attributes loaded and appended before eager loads?)
2. I removed the attribute from the $appends
. Then I intended to loop through all pupils in a single view. below is the code. which still doesn’t work.
foreach($school->pupils as $pupil){
$pupil->threaded_comments.
}
Can anyone offer advice on this? Thanks
Edits: why is it so hard to paste code blocks !!?
submitted by /u/vibezad
[link] [comments]
from Laravel Questions and Answers https://laravelquestions.com/rlaravel/disable-appends-when-calling-a-collection/
via Lzo Media
No comments:
Post a Comment