Laravel 4 mapToGroups()
Laravel 4 mapToGroups()
我试图映射到 Laravel 4 中的一个组,但它给我一个错误:
$groups = $this->messages->mapToGroups(function($message, $key){
return [
$message->sent_at => [
$message
]
];
});
我得到的错误是:
Call to undefined method Illuminate\Database\Eloquent\Collection::mapToGroups()
4.2版本是否支持该功能?
根据这条推文; https://twitter.com/laravellog/status/857629925834203136?lang=en
提交合并; https://github.com/laravel/framework/pull/18949/commits/1a36e74e4fd1b5a5825242e154154394788c7d3d
此功能已添加到 laravel 5.4.20
及更高版本。
因此,4.x
可能不支持它
您可以在需要 mapToGroup 的任何地方将此函数包含在 class 中(请注意,它改编自 L.5.4
中的 mapToGroups
函数
/**
* Run a grouping map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @param array $array the array to map to group
* @return Collection
*/
public function mapToGroups(callable $callback, $array)
{
$groups = (new Collection($array))->map($callback)->reduce(function ($groups, $pair) {
$groups[key($pair)][] = reset($pair);
return $groups;
}, []);
return (new Collection($groups))->map([Collection::class, 'make']);
}
因此,如果将所有用户映射到组,则示例如下:
$users = User::all()->toArray();
return $this->mapToGroups(function($message, $key){
return [
$message['created_at'] => [
$message
]
];
}, $users);
使用这个会给你想要的答案。
PS: I cannot guarantee that this would work on L4.2 but I checked the main functions that mapToGroups
requires i.e map
and reduce
function which is available in L4.2 Collection class too.
我试图映射到 Laravel 4 中的一个组,但它给我一个错误:
$groups = $this->messages->mapToGroups(function($message, $key){
return [
$message->sent_at => [
$message
]
];
});
我得到的错误是:
Call to undefined method Illuminate\Database\Eloquent\Collection::mapToGroups()
4.2版本是否支持该功能?
根据这条推文; https://twitter.com/laravellog/status/857629925834203136?lang=en
提交合并; https://github.com/laravel/framework/pull/18949/commits/1a36e74e4fd1b5a5825242e154154394788c7d3d
此功能已添加到 laravel 5.4.20
及更高版本。
因此,4.x
可能不支持它您可以在需要 mapToGroup 的任何地方将此函数包含在 class 中(请注意,它改编自 L.5.4
中的mapToGroups
函数
/**
* Run a grouping map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @param array $array the array to map to group
* @return Collection
*/
public function mapToGroups(callable $callback, $array)
{
$groups = (new Collection($array))->map($callback)->reduce(function ($groups, $pair) {
$groups[key($pair)][] = reset($pair);
return $groups;
}, []);
return (new Collection($groups))->map([Collection::class, 'make']);
}
因此,如果将所有用户映射到组,则示例如下:
$users = User::all()->toArray();
return $this->mapToGroups(function($message, $key){
return [
$message['created_at'] => [
$message
]
];
}, $users);
使用这个会给你想要的答案。
PS: I cannot guarantee that this would work on L4.2 but I checked the main functions that
mapToGroups
requires i.emap
andreduce
function which is available in L4.2 Collection class too.