php - 如何从 laravel 中的数据库中选择最后一行

标签 php laravel laravel-5.6

<分区>

  public function addNewPost(Request $request)/****ADD new POST****/
  {
    $this->validate($request,['post_title'=>'required|min:4|max:100',
                              'post_description'=>'required|min:20|max:500'
                            ]);    

    $user_name = Session::get('name');
    $post_title = $request->input('post_title');
    $post_description = $request->input('post_description');


    $addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
    $addPost->save();
    $addPost->post_id;
    //$addPost = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->get();

    print_r($addAdmin->post_id); //This is printing nothing, i.e. blank.     
  }
userposts 表中的

post_id 列自动递增。我正在尝试通过 user_name 获取用户的最后一个帖子 ID。我看过一些教程,也通过互联网检查了一些问题,但无法做我想做的事情。任何人都可以知道如何去做。谢谢。

最佳答案

在查询中尝试使用 first() 而不是 get() 可能对您有帮助

 $lastdata = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->first();

print_r($lastdata);

关于php - 如何从 laravel 中的数据库中选择最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193853/

相关文章:

php - artisan 迁移访问被拒绝

mysql - Laravel 中使用一个函数向多个表中插入数据

php - Passport 通过访问 token 获取用户 Laravel 5.3

php - Laravel:如何在没有数据库的情况下对用户进行身份验证

php - 如何从有条件的表中选择所有数据?

php - 如何使用 PHP 删除外部数组

php - mysqli fetch_assoc 使用 foreach 删除第一行

php - Laravel Lumen 5.7,debugbar throw Call to a member function listen on null

拉拉维尔 5 : How to use array_get method to access an attribute with a dot inside

php - Laravel - 视频文件验证