Reputation: 841
I've run into this issue a couple of times now and I can't seem to find a solution - I feel like I'm missing something obvious.
I am making a JSON API with Lumen, building up specific routes for specific use cases. To speed up load times, I only want to output the fields I will be using.
My model has a combination of fields, relations and attributes. I am struggling to specify the attribute when limiting output
For example:
A task
has time_records
. Each time_record
has a value
of time
.
I want to output the task names, time record values plus an attribute of totalTime
which I have set on the task
like the below (this isn't the full code but hopefully it gets across the idea)
class Task extends Model {
protected $appends = [
'totalTime'
];
public function timeRecords() {
return $this->hasMany('TimeRecord');
}
public function getTotalTimeAttribute() {
$total = $this->timeRecords()->map(function($time_record){
return $time_record->value;
});
return array_sum($total);
}
}
If I then do the following:
Task::get();
And output that, I get all the tasks with the totalTime
attribute. However, as mentioned I want to only output some attributes:
Task::select('id', 'name')
->with([
'timeRecord' => function($query){
$query->select('id');
}
])
No matter what I do, I can't seem to get the attribute output with that. The value is there in the array, but is null.
Upvotes: 1
Views: 1553
Reputation: 2901
You can get that using with()
method without callback. Callback method provide you to filter results..
Task::select('id', 'name')
->with("timeRecords:id") // use comma for multiple columns
->get();
Upvotes: 1
Reputation: 841
To resolve this, you have to select the fields that the attribute accesses.
Because I was only returning the ID of the time_record
, the attribute was unable to calculate the total_time
as the value
field was not available.
(Was only while writing this question out did I discover the answer... 🙄)
Upvotes: 2