你可以为所欲为,但你必须使用sort()
方法,而不是sortBy()
方法。该sort()
方法将采用一个闭包,您可以使用它来定义您的自定义排序算法。基本上,如果您将闭包传递给sort()
,它会usort()
使用您的闭包调用 PHP 来对项目进行排序。
这只是您要查找的内容的粗略概念。您可能需要对其进行调整,因为您发布的内容几乎没有不确定性。您可以将其定义为要传入的实际函数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()
工作的更多信息,您可以查看文档。