如何 select laravel 中数据库的最后一行

How to select the last row from database in laravel

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

post_iduserposts table 自动递增。我试图通过 user_name 获取用户的最后一个 post id。我看过一些教程,也通过互联网检查了一些问题,但无法做我想做的事情。任何人都可以知道如何去做。谢谢。

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

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

print_r($lastdata);

Laravel 具有您可以使用的 last() 方法。

这是来自文档:

last()

The last method returns the last element in the collection that passes a given truth test:

collect([1, 2, 3, 4])->last(function ($value, $key) { return $value < 3; }); // returns 2

You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

collect([1, 2, 3, 4])->last(); //returns 4

以下是仅获取最后一个 ID 的示例:

Model::pluck('id')->last();

不需要太多处理的简单方法是

DB::getPdo()->lastInsertId();

希望对您有所帮助

你也可以试试

 $addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPost->save();
$addPost->update();
print_r($addPost->post_id); //It will print id..     

P.S第二种方法有点多余

希望对您有所帮助

DB::table('userposts')->last()->pluck('user_name')是最快的方法。 确保首先应用 last() 以避免不必要的工作量

请仔细查看您的打印声明:

print_r($addAdmin->post_id);

$addAdmin 未在您的函数范围内定义。从 数据库 获取 last 行的最佳方法:

DB::table('name_of_table')->last()->pluck('user_name')

这里是使用数据库的文档:https://laravel.com/docs/5.6/database