laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Eloquent: order by field #1066

Open martinbean opened 6 years ago

martinbean commented 6 years ago

Could an order by field method by added to Eloquent? Most relational databases allow sorting a field by values, i.e. in MySQL:

SELECT * FROM `plans` ORDER BY FIELD(`interval`, 'day', 'week', 'month', 'year');

I could use orderByRaw() for this, but there are a couple of issues:

Usage-wise, I see it looking like this:

$plans = Plan::orderByField('interval', ['day', 'week', 'month', 'year'])->get();
andreshg112 commented 5 years ago

I just created a trait to accomplish this: https://gist.github.com/andreshg112/b359089878bdb2269321838d8921f429

staudenmeir commented 5 years ago

This syntax is only supported by MySQL.

The other databases require a different solution: https://stackoverflow.com/a/1310188/4848587

martinbean commented 5 years ago

@staudenmeir It’s a good job queries are crafted by database-specific grammar classes under the hood, then…