【问题标题】:Last record id not fetched properly in laravel在 laravel 中未正确获取最后一条记录 id
【发布时间】:2020-04-10 07:07:14
【问题描述】:

我正在尝试在 laravel 6 中检索我的订阅表的最后一条记录 id

以下是我的功能

public function activateApp($id)
    {
        $app = App::where('appId','=',$id)->firstOrFail();
        if($app->payment_option == 'monthly')
        {
            $renewDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime("+30 day"))));
        }
        else
        {
            $renewDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime("+365 day"))));
        }

        $lastdata = DB::table('subscriptions')->orderBy('id', 'desc')->first();
        //dd($lastdata);
        //die();

        //update app table records
        DB::table('apps')
            ->where('appId', $id)
            ->update([
                'status' => $lastdata,
                'renewDate' => $renewDate
            ]);

        return redirect()->route('home');
    }

我用过

$lastdata = DB::table('subscriptions')->orderBy('id', 'desc')->first();

获取 id,但是当我尝试从该值更新我的应用程序表 ststus 列时,它似乎不起作用,它没有更新,甚至没有给出错误..即使“dd”也不起作用也是。

(在获取最后一条记录后,整个函数似乎停止工作)

【问题讨论】:

    标签: php mysql laravel laravel-5 laravel-6


    【解决方案1】:

    您正在尝试使用整个 $lastdata 对象更新 status

    我不知道你的数据库架构,但也许你应该尝试类似

                DB::table('apps')
                    ->where('appId', $id)
                    ->update([
                        'status' => $lastdata->status,
                        'renewDate' => $renewDate
                    ]);
    

    您还可以仔细检查数据库subscriptions 是否有行且不为空。

    【讨论】:

      【解决方案2】:

      您将使用订阅对象更新状态字段。还有一件事是您不需要像已经拥有的那样再次检索应用程序对象,因此只需更改值并保存即可。

      public function activateApp($id) {
          $app = App::where('appId','=',$id)->firstOrFail();
          if($app->payment_option == 'monthly')
          {
              $renewDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime("+30 day"))));
          }
          else
          {
              $renewDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime("+365 day"))));
          }
      
          $lastdata = DB::table('subscriptions')->orderBy('id', 'desc')->first();
      
          //update app table records
          $app->status = $lastdata->status;
          $app->renewDate = $renewDate;
      
          if ($app->save()) {
              return redirect()->route('home');
          } else {
              // show some error page.
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-01
        • 2012-01-25
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 2018-06-26
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        相关资源
        最近更新 更多