問題描述
我的員工和組表之間存在多對(duì)多關(guān)系.我已經(jīng)創(chuàng)建了數(shù)據(jù)透視表,并且一切正常.但是,我的員工表上有一個(gè) sortOrder 列,用于確定它們的顯示順序.sortOrder 列中值為 1 的員工應(yīng)該排在第一位,值為 2 的員工排在第二位,依此類推.(如果按降序排序,則向后) sortOrder 列是一個(gè)允許空值的整數(shù)列.
I've got a many to many relationship between my employees and groups table. I've created the pivot table, and all is working correctly with that. However, I've got a sortOrder column on my employees table that I use to determine the order in which they display. Employee with a value of 1 in the sortOrder column should be first, value of 2 should be second, so on. (Or backwards if sorted descending) The sortOrder column is a integer column that allows null values.
我已經(jīng)設(shè)置了我的組模型來(lái)按排序列對(duì)員工進(jìn)行排序,但是我遇到了一個(gè)問題.始終首先顯示空值.我已經(jīng)嘗試使用 ISNULL 和類似的 SQL 方法來(lái)代替使用的常規(guī)asc"或desc",但我只得到一個(gè)錯(cuò)誤.
I've set up my group model to sort the employees by the sort column, but I've run into a problem. The null values always are displayed first. I've tried using ISNULL and similar SQL methods in place of the regular "asc" or "desc" used, but I only get an error.
這是我的組模型中的代碼:
Here's the code in my Group model:
class Group extends Eloquent {
public function employees()
{
return $this->belongsToMany("Employee")->orderBy('sortOrder', 'asc');
}
}
這是我在控制器中用來(lái)訪問我的模型的內(nèi)容:
And here's what I use in the controller to access my model:
$board = Group::find(6)->employees;
Laravel 中最后對(duì) NULL 值進(jìn)行排序的技巧是什么?
What's the trick in Laravel to sorting NULL values last?
推薦答案
Laravel 沒有考慮 ISNULL
方法,但是你可以將它作為原始查詢傳入并仍然使用它因?yàn)樗?IF
語(yǔ)句更有效,并且如果您的員工人數(shù)超過(guò) 1000000 人(已接受的答案),結(jié)果將保持不變,如下所示:
Laravel does not take into consideration the ISNULL
method however, you can pass it in as a raw query and still make use of it as it's more efficient than IF
statements and the results will stay the same if you ever go beyond 1000000 employees (accepted answer), like so:
public function employees()
{
return $this->hasMany('Employee')
->orderBy(DB::raw('ISNULL(sortOrder), sortOrder'), 'ASC');
}
更新:您還可以使用 orderByRaw() 方法:
Update: You can also use the orderByRaw() method:
public function employees()
{
return $this->hasMany('Employee')
->orderByRaw('ISNULL(sortOrder), sortOrder ASC');
}
這篇關(guān)于如何在 Laravel 中使用 Eloquent 最后對(duì) NULL 值進(jìn)行排序的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!