Laravel Eloquent Pluck 不会丢失钥匙

时间:2023-03-04
本文介绍了Laravel Eloquent Pluck 不会丢失钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 Laravel 中有以下集合:

I have the following collection in Laravel:

 ["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]

如果我运行以下代码:

$TheEpisode->TheNumbers->pluck('episodeNumber');

我会得到以下结果:

[100,210]

我想保留每个号码的密钥,我该如何实现?

I would like to keep the keys for each number, how can I achieve this?

这是我的预期结果:

[{"episodeNumber":100},{"episodeNumber":210}]

PHILIS PETERS(改进)

TheEpisode->TheNumbers->reduce(function ($result, $episode) {
          $episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
          $result[] = $episodeData;
          return $result;
        }));

推荐答案

尝试这样的事情,它应该可以使用 map...

Try something like this, it should work using map...

return $TheEpisode->TheNumbers->map(function ($episode) {
    return ['episodeNumber' => $episode['episodeNumber']];
});

这篇关于Laravel Eloquent Pluck 不会丢失钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Laravel eloquent 集合上的 Array_unique 下一篇:Laravel Eloquent orWhere 查询

相关文章