【问题标题】:Get latest inserted records Laravel获取最新插入的记录 Laravel
【发布时间】:2018-03-08 11:47:28
【问题描述】:

我将多个帖子存储在一个模型中,例如:

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

现在,如果我有20 users,我将拥有20 new Posts

问题:

save() 之后的 20 个帖子如何取回?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以像这样获得一组插入的帖子:

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

    您也可以在foreach 循环之后将其转换为集合:

    $posts = collect($posts);    
    

    【讨论】:

      【解决方案2】:

      你应该试试这个:

      $rsltPosts = Post::orderBy('id', 'desc')
                     ->limit(20)
                     ->get();
      

      【讨论】:

        猜你喜欢
        • 2015-02-02
        • 2014-05-07
        • 2018-11-06
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 2017-02-15
        • 2017-07-04
        • 1970-01-01
        相关资源
        最近更新 更多