如何从集合项中获取密钥?
$posts= Post::all();
示例(不起作用):
$key = $posts->where('id', $id)->getKey();
all()
将返回没有钥匙的集合。如果你在谈论0,1,2等整数键,请使用search()
方法:
$key = $posts->search(function($i) use($id) {
return $i->id === $id;
});
试试$post_ids = Post::pluck('id');
它只从所有id
记录中获取Post
列并将它们作为集合返回。
如果只想要一个普通数组,请添加toArray():
$post_ids = Post::pluck('id')->toArray();