1 回答

TA貢獻(xiàn)1851條經(jīng)驗 獲得超5個贊
結(jié)果可以使用字符串按字符串排序case:
public function sizes(){
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("
CASE name WHEN 'SM' THEN 1
WHEN 'MD' THEN 2
WHEN 'LG' THEN 4
WHEN 'XL' THEN 5
WHEN 'XXL' THEN 6
ELSE 7 END ASC"));
}
有更短的選項,但它們不適用于每個數(shù)據(jù)庫實現(xiàn):
Mariadb:https ://mariadb.com/kb/en/library/find_in_set/
Mysql:https : //dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set
mysql
在find_in_setMySQL的應(yīng)該是這樣的:
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM','MD','LG','XL', 'XXL')"));
瑪麗亞數(shù)據(jù)庫
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM,MD,LG,XL,XXL')"));
- 1 回答
- 0 關(guān)注
- 268 瀏覽
添加回答
舉報