我有方法,我ArticlesController爲根據要求GET參數排序的文章:爲什麼不進行排序的回調工作?
protected static function sortArticles(Collection $articles, string $sort_by, string $order): Collection
{
$sortBy = function ($by, $order) use ($articles) {
if ($order === 'asc') {
$method = 'sortBy';
} elseif ($order === 'desc') {
$method = 'sortByDesc';
}
return call_user_func([$articles, $method], [$by]);
};
switch ($sort_by) {
case 'title':
return $sortBy('title', $order);
break;
case 'views':
return $sortBy('views_count', $order);
break;
case 'comments':
return $sortBy(function ($article) { // This is my callback for sorting and it doesn't work as expected
return count($article->comments);
}, $order);
break;
case 'date':
return $sortBy('created_at', $order);
break;
}
}
一切工作正常,但是當sort_by =評論(在交換機3的情況下),它只是不工作:
(1/1)班閉幕ErrorException對象無法轉換爲字符串
不知道爲什麼,在sortByDesc法上所謂的上校通過call_user_func lection實例不接受Closure作爲參數並嘗試將其轉換爲字符串。 如果我直接打電話sortBy或sortByDesc上收集,一切工作正常:
case 'comments':
return $articles->sortBy(function ($article) { // Gives no errors
return count($article->comments);
});
break;
你不能只使用'count($ article-> comments)'作爲參數而不是關閉嗎? –
@NathanHeffley那麼在這種情況下會計算什麼呢? sortBy()的參數必須是包含元素屬性名稱的字符串,或者每個Collection元素的Closure返回值。 https://laravel.com/docs/5.5/collections#method-sortby – Audiophile
你想根據評論的數量進行排序,而不是通過評論本身進行排序......你正在返回一個計數,其中call_user_func期望$是哪個字段名字...因此字符串問題... – Serge