简体   繁体   English

在 Laravel 中按 Eloquent 排序

[英]Order by Eloquent in Laravel

I have a table in my database that has a field called round with the following records我的数据库中有一个表,它有一个名为 round 的字段,其中包含以下记录

  • Regular Season -1常规赛-1
  • Regular Season -2常规赛季-2
  • Regular Season -10常规赛-10
  • Regular Season -11常规赛-11
  • Regular Season -21常规赛-21

etc等等

but when ordering with orderBy ('round') I returned them like that但是当使用orderBy ('round')订购时,我就这样返回了它们

  • Regular Season -1常规赛-1
  • Regular Season -10常规赛-10
  • Regular Season -11常规赛-11
  • Regular Season -2常规赛季-2
  • Regular Season -21常规赛-21

and I need it consecutively我连续需要它

You can store round as a signed integer column instead of string in your DB:您可以将round存储为带符号整数列而不是数据库中的字符串:

$table->integer('round');
$table->string('type');

Now you can use orderBy('round') to get desired result.现在您可以使用orderBy('round')来获得所需的结果。

You may also define an accessor on your model for round like this:您还可以在您的模型上为round 定义一个访问器,如下所示:

/**
 * Get the formatted round value.
 *
 * @return string
 */
public function getRoundAttribute($value)
{
    return "{$this->type} {$value}";
}

Your column is text-based and therefore is sorted alphabetically , not numerically .您的列是基于文本的,因此按字母顺序排序,而不是按数字排序。 Split your database column into two:将您的数据库列一分为二:

$table->string('round');           // e.g. "Semifinals", "Regular Season"
$table->integer('round_number');   // e.g. 1, 2, 3, ... , 10

Then you can do ->orderBy('round', 'asc')->orderBy('round_number', 'asc');然后你可以做->orderBy('round', 'asc')->orderBy('round_number', 'asc');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM