从收集项中获取密钥

问题描述 投票:-1回答:2

如何从集合项中获取密钥?

$posts= Post::all();

示例(不起作用):

$key = $posts->where('id', $id)->getKey();

php laravel collections
2个回答
0
投票

all()将返回没有钥匙的集合。如果你在谈论0,1,2等整数键,请使用search()方法:

$key = $posts->search(function($i) use($id) {
    return $i->id === $id;
});

0
投票

试试$post_ids = Post::pluck('id');

它只从所有id记录中获取Post列并将它们作为集合返回。

如果只想要一个普通数组,请添加toArray():

$post_ids = Post::pluck('id')->toArray();

© www.soinside.com 2019 - 2024. All rights reserved.