【问题标题】:How to update last row in table in laravel?如何更新laravel表中的最后一行?
【发布时间】:2019-09-12 21:02:17
【问题描述】:

我想在 laravel 应用程序的 db 表中更新用户的最后一行数据。 我尝试使用 orderBy id desc limit 1 但它无法工作。

DB::table('shortcontacts')->where('mobile',($data->mobile))->update(['otp_stts'=>'Verified'])->orderBy('id','desc')->first();

【问题讨论】:

  • 我正在尝试,它已更新所有行。我只想要最后一个。

标签: php mysql laravel sql-update


【解决方案1】:

您应该将数据排序为 desc 然后像这样更新:

DB::table('shortcontacts')->where('mobile',($data->mobile))->orderBy('id','desc')->first()->update(['otp_stts'=>'Verified']);

【讨论】:

  • DB::table('shortcontacts')->where('mobile',($data->mobile))->update(['otp_stts'=>'Verified'])-> orderBy('id','desc')->first();
  • 你不能用 update 方法链接 orderBy('id','desc') 因为更新返回整数,所以更新然后获取其他变量中的数据
  • 我不想获取数据。我只需要更新用户插入的最后一行。
【解决方案2】:

请尝试以下代码:

  $post = Post::orderBy('id', 'DESC')->first();
  $post->{column_name} = {value};
  $post->save();

【讨论】:

    【解决方案3】:

    您可以按降序排列模型的数据,然后像这样选择第一个:

    $lastUser = App\User::orderBy('created_at', 'desc')->first();
    

    在你可以像这样更新你的模型之后:

    $lastUser->name = "New Name"; 
    $lastUser->save();
    

    更新:您还可以使用 id 字段而不是“created_at”来对数据进行排序。

    【讨论】:

      【解决方案4】:

      最新和最旧的方法可让您轻松按日期排序结果。默认情况下,结果将按 created_at 列排序。或者,您可以传递您希望排序的列名:

      $last = DB::table('shortcontacts')
                      ->latest()
                      ->first();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-18
        • 2021-02-08
        • 1970-01-01
        • 1970-01-01
        • 2016-05-31
        • 2015-01-03
        • 2021-04-02
        • 2021-06-09
        相关资源
        最近更新 更多