[Feature request/package idea?] JSON attribute casting #41752
Unanswered
sneakylenny
asked this question in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The problem
I would like to be able to cast JSON attributes to data types on the database side. The reason is, when I want to sort by a JSON attribute that happens to be an
int
it wouldn't sort alphabetically but numerically. Which makes sense since there is no way SQL knows it's an integer because JSON doen't have defined data-types.I really like the feature where we can query things in json columns like
But as stated before, when I this:
the rows get sorted by the attribute alphabetically not numerically. However there is a way to solve this.
Normally when running the line above it would send a query like this:
But if the value would be cast like this:
it would be sorted based on the casted type:
unsigned
.My workaround
Reason
Since I actually needed this feature I've tried to implement it myself.
You would ask: "But why not use collections and use
->orderBy()
?"Well, I've tried but it would make navigating pages in my server rendered table take about 2 seconds. Which is unacceptable, Using SQL is simply WAY faster:
What I did
ModelWithJson
by callingphp artisan make:model ModelWithJson
HasJsonColumns
by callingphp artisan make:model \App\Concerns\HasJsonColumns
(correct me if it should be\App\Traits\...
instead). This contains all the logic for obtaining a json attribute as column and cast it into a datatype if needed.App\Concerns\HasJsonColumns
The result:
With all this in place I can now include these columns and sort by them without having to import all records or add more columns.
My simplified example:
The data will now be ordered descending based on the prop inside the json:
I hope someone who also has this problem stumbles across this discussion, if so, I hope this helped! :)
The best case is of course if Laravel would have a similar feature built in.
Beta Was this translation helpful? Give feedback.
All reactions