简体   繁体   中英

Order by Eloquent in Laravel

I have a table in my database that has a field called round with the following records

  • Regular Season -1
  • Regular Season -2
  • Regular Season -10
  • Regular Season -11
  • Regular Season -21

etc

but when ordering with orderBy ('round') I returned them like that

  • Regular Season -1
  • Regular Season -10
  • Regular Season -11
  • Regular Season -2
  • Regular Season -21

and I need it consecutively

You can store round as a signed integer column instead of string in your DB:

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

Now you can use orderBy('round') to get desired result.

You may also define an accessor on your model for round like this:

/**
 * 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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