問(wèn)題是:怎樣才能用添加的總分?jǐn)?shù)(total)屬性進(jìn)行排序
場(chǎng)景:
Users表
ID | 姓名 | 語(yǔ)言 | 數(shù)學(xué) | 英語(yǔ)
-----------------------------------------
1 | 張三 | 99 | 78 | 66
-----------------------------------------
2 | 李四 | 50 | 100 | 87
-----------------------------------------
3 | 王五 | 88 | 91 | 87
添加的屬性 總分?jǐn)?shù)(total)
class User extends Model
{
protected $appends = ['total'];
public function getTotalAttribute () {
$yuwen = $this->attributes['yuwen'];
$shuxue = $this->attributes['shuxue'];
$yingyu = $this->attributes['yingyu'];
return $yunwen + $shuxue + $yingyu;
}
}
如果語(yǔ)文的分?jǐn)?shù)排序時(shí)是:
class UserController extends Controller
{
public function userListApi()
{
$datas = User::orderBy('yuwen', 'dsec')->paginate(10);
return response()->json($datas);
}
}
怎么樣才能讓添加的屬性 total 參與排序呢?
3 回答

胡子哥哥
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果是要查詢數(shù)據(jù)庫(kù)時(shí)的排序, 你需要手工添加一個(gè)字段, ->select(DB::raw('幾個(gè)字段相加 as total'))->orderby('total');
如果是查出來(lái)后, 再排序, 那可以使用 Collection::sortBy() 函數(shù)排序.

蠱毒傳說(shuō)
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果getAttribute 是一個(gè)比較復(fù)雜邏輯取出來(lái)的數(shù)據(jù), 可以直接用 getAttribute 排序么?
- 3 回答
- 0 關(guān)注
- 772 瀏覽
添加回答
舉報(bào)
0/150
提交
取消