Open ibrahimalanshor opened 9 months ago
At the moment, you'd need to add an accessor to your model and get it like that. (The advantage to that approach though is you can then use it in other places in your code, i.e. not just in JSON:API.)
Note that it won't be efficient though if you're retrieving zero-to-many of the resource, because you'll get an n+1 problem with the query.
@lindyhopchris How would that work with a filter, though? Pretty sure you can't access filters in an accessor.
Yeah it wouldn't work with a filter. If we wanted to get it working in a filter, someone would need to share what the query is on the Eloquent model (i.e. how you do the query on the model outside of Laravel JSON:API) and then that should be transferrable to a Laravel JSON:API filter.
How do I create a custom attribute in a schema that results from the SUM function? For instance, there's a
products
table with a has-many relationship toproduct_prices
and a many-to-many relationship tomaterials
throughmaterial_products.
I want to display all products with a columnprice
that results from summing allprice
columns inproduct_prices
and the product of theqty
column inmaterial_products
with theprice
column inmaterials
' Here's an example SQL code:This SQL query calculates and displays the
final_price
attribute as the sum ofproduct_price
andmaterial_price
for each product. Alternatively, should I use a model accessor for this purpose?