首页 > 解决方案 > Laravel 在没有 foreach 的情况下获取集合的 id

问题描述

我的代码目前如下所示:

foreach ($things as $thing) {
            $ids[] = $thing->id;
        }
dd(Other::whereIn('thing_id', $ids)->get());

事物模型有很多 Other

    public function others()
    {
        return $this->hasMany(Other::class);
    }

它正在工作,但是我可以在不使用 foreach 的情况下实现此功能吗?对我来说似乎并不干净。我试图把整个收藏品放在这样的地方:

dd(Other::whereIn('thing_id', $things)->get());

但这仅在 id 为 1 的地方返回。

我正在寻找清理此代码的帮助,任何帮助表示赞赏。

标签: laraveleloquent

解决方案


有一个功能叫做“pluck”

您可以将其应用于集合,如下所示

$collection->pluck('id');

更多可以在文档上看到

https://laravel.com/docs/7.x/collections#method-pluck


推荐阅读