I am cleaning up a quite messy php laravel 8 project right now.
Currently my ressource looks like this:
class MyModelSimpleResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'my_calculated_attribute' => MyModel::whereRaw('fk_id = ? AND model_type = "xyz"', [$this->id])->count(),
];
}
}
My problem is that on calling the API endpoint, for every record of MyModel
it creates a separate query to calculate my_calculated_attribute
.
I know that you can define foreign key constrains in the model like and query like this:
MyModel::with('myFkModel')->get()
This works great for foreign keys. But how can I avoid n queries when I need this my_calculated_attribute
.
Thanks a lot!
PS: I know that raw queries are a bad idea and I know that the resource is supposed to transform data and not query it. 😅
source https://stackoverflow.com/questions/69003372/avoiding-n-queries-on-api-list-call-for-database-calculated-model-attributes
Comments
Post a Comment