你可以做你想做的,但你必須使用sort()
方法,而不是sortBy()
方法。 sort()
方法將採用閉包,您可以使用它來定義自定義排序算法。基本上,如果您通過關閉sort()
,它會調用PHP的usort()
與您的關閉排序項目。
這只是你正在尋找什麼的粗略想法。您可能需要調整它,因爲您發佈內容的不確定性很少。您可以將其定義爲一個實際功能,以便傳入sort()
,或者您可以將其作爲匿名函數傳遞給sort()
。
function ($a, $b) {
/**
* Your question states that project is a belongsToMany relationship.
* This means that project is a Collection that may contain many project
* objects, and you need to figure out how you want to handle that. In
* this case, I just take the max projectid from the Collection (max,
* since this field will be sorted desc).
*
* If this is really just a belongsTo, you can simplify this down to
* just $a->project->projectid, etc.
*/
$aFirst = $a->project->max('projectid');
$bFirst = $b->project->max('projectid');
/**
* If the projectids are equal, we have to dig down to our next comparison.
*/
if ($aFirst == $bFirst) {
/**
* Since the first sort field (projectids) is equal, we have to check
* the second sort field.
*/
/**
* If the dates are equal, we have to dig down to our next comparison.
*/
if ($a->date == $b->date) {
/**
* Your question states that user is a belongsToMany relationship.
* This means that user is a Collection that may contain many user
* objects, and you need to figure out how you want to handle that.
* In this case, I just take the min username from the Collection
* (min, since this field will be sorted asc).
*/
$aThird = $a->user->min('username');
$bThird = $b->user->min('username');
/**
* If the final sort criteria is equal, return 0 to tell usort
* that these two array items are equal (for sorting purposes).
*/
if ($aThird == $bThird) {
return 0;
}
/**
* To sort in ascending order, return -1 when the first item
* is less than the second item.
*/
return ($aThird < $bThird) ? -1 : 1;
}
/**
* To sort in descending order, return +1 when the first item is
* less than the second item.
*/
return ($a->date < $b->date) ? 1 : -1;
}
/**
* To sort in descending order, return +1 when the first item is
* less than the second item.
*/
return ($aFirst < $bFirst) ? 1 : -1;
}
欲瞭解更多有關如何usort()
的作品,你可以check the docs。
你想在這裏做什麼?你正在嘗試創建一個新的集合還是對現有的集合進行排序? –
基本上,我檢索數據,並有關係的雄辯集合。我正在整理現有的一個。 – user3882878
然後,如果您按多個條件對它們進行排序,結果將會混合。因爲你不能保證與最大ID的人也有最大日期,也有最大名稱 –