Replies: 1 comment 1 reply
-
What I do for these sorts of "stats" type relationships is create a database view and add a model over it, setting the relationships as appropriate. You can use migrations to manage those views, but you tend to need to create/manage them as statements in the sql of your database, so you lose the DB agnostic nature of Laravel (not a problem in my case). Another option might be a subquery join on a self-join of the user in the user model. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
TL;DR
I would like to define a way for a whole model to be casted to a scalar/object, etc. Similar to an attribute.
Long version
Let's say we have two tables
users
and areviews
:users
tablereviews
tableAnd we have 2 models:
and
I would like to get multiple users at one, while also calculating their rating.
I have considered adding an accessor:
but it will generate one query (
$this->reviews()->average('stars')
) for each user. Looking at the accessor documentation it seems that an accessor is something to transform an existing value. on a model (and not a computed value, as i am considering).Since calculating a rating is a data crunching issue, for which a database is uniquely suited, i can calculate all the ratings for all users like so:
And the php class equivalent of this sql is (in my humble opinion)
and i can add this as a relationship on the
User::class
:So that i can get the rating (which is like a "computed" field of the
User::class
):Looking at the documentation a model:
RatingAttribute::class
)RatingAttribute::class
)I see no need to have a 1:1 for each model to have a corresponding table.
I would like to define a model as being castable when it's resolved as a relationship:
Beta Was this translation helpful? Give feedback.
All reactions