簡體   English   中英

在 Laravel 中按 Eloquent 排序

[英]Order by Eloquent in Laravel

我的數據庫中有一個表,它有一個名為 round 的字段,其中包含以下記錄

  • 常規賽-1
  • 常規賽季-2
  • 常規賽-10
  • 常規賽-11
  • 常規賽-21

等等

但是當使用orderBy ('round')訂購時,我就這樣返回了它們

  • 常規賽-1
  • 常規賽-10
  • 常規賽-11
  • 常規賽季-2
  • 常規賽-21

我連續需要它

您可以將round存儲為帶符號整數列而不是數據庫中的字符串:

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

現在您可以使用orderBy('round')來獲得所需的結果。

您還可以在您的模型上為round 定義一個訪問器,如下所示:

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

您的列是基於文本的,因此按字母順序排序,而不是按數字排序。 將您的數據庫列一分為二:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM