获取最新插入的记录Laravel [英] Get latest inserted records Laravel
本文介绍了获取最新插入的记录Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在像这样的模型中存储多个帖子:
I am storing multiple posts in a model like:
foreach($users as $user)
{
$post = new Post;
$post->user_id = $user->id;
$post->save();
}
现在,如果我有20 users
,我将拥有20 new Posts
,
Now if I have 20 users
I will have 20 new Posts
,
问题:
在save()
之后,我如何找回20条帖子?
How do I get the 20 posts back after save()
?
推荐答案
您可以获取一系列插入的帖子,如下所示:
You can get an array of inserted posts like this:
$posts = [];
foreach($users as $user) {
$post = new Post;
$post->user_id = $user->id;
$post->save();
$posts[] = $post;
}
您还可以在foreach
循环之后将其转换为集合:
You also can convert it to a collection after the foreach
loop:
$posts = collect($posts);
这篇关于获取最新插入的记录Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文