1 回答
TA贡献1851条经验 获得超5个赞
结果可以使用字符串按字符串排序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"));
}
有更短的选项,但它们不适用于每个数据库实现:
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的应该是这样的:
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM','MD','LG','XL', 'XXL')"));
玛丽亚数据库
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM,MD,LG,XL,XXL')"));
- 1 回答
- 0 关注
- 241 浏览
添加回答
举报