Get latest inserted records Laravel

2019-08-24 02:37发布

I am storing multiple posts in a model like:

foreach($users as $user)
{
   $post = new Post;
   $post->user_id = $user->id;
   $post->save();
}

Now if I have 20 users I will have 20 new Posts,

Question:

How do I get the 20 posts back after save() ?

2条回答
冷血范
2楼-- · 2019-08-24 02:49

You should try this:

$rsltPosts = Post::orderBy('id', 'desc')
               ->limit(20)
               ->get();
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-24 02:55

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;
}

You also can convert it to a collection after the foreach loop:

$posts = collect($posts);    
查看更多
登录 后发表回答