我有一個食物模型。每種食物都有價格和折扣(百分比)。我附加了一個成本屬性來保存一個基于第一個價格和折扣計算的值。示例:我們有一個價格為 10 美元的食品。折扣是10%,所以成本是9 $。class Food extends Model{ protected $appends = ['cost']; public function getCostAttribute() { return $this->price - round( ($this->price*$this->discount) / 100 ); }}我需要根據成本訂購食物。我不能使用,因為成本實際上不是一列。所以我必須使用.orderBysortBy$foods = Food::all();$foods = $foods->sortBy(function($food){ return $food->cost;});現在,如何對變量進行分頁?因為我無法執行以下代碼進行分頁$foods$foods = $foods->paginate(12);
2 回答

汪汪一只貓
TA貢獻1898條經驗 獲得超8個贊
sort by
已經從db中獲取數據,因此使用分頁并沒有真正的幫助。
所以我建議像這樣更改你的代碼,這將降低IO成本:
Food::select('*', DB::raw('(price - round((price * discount) / 100)) AS cost') )->orderBy('cost') ->paginate(12)

胡子哥哥
TA貢獻1825條經驗 獲得超6個贊
您必須使用聯接來根據關系模型對項目進行排序。試試這個
$order = 'desc';
$users = Food::join('costs', 'foods.id', '=', 'costs.id')->orderBy('costs.id',
$order)->select('foods.*')->paginate(10);
參考資料 : [https://laracasts.com/discuss/channels/eloquent/order 關系][1]
- 2 回答
- 0 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消