获取最近创建的数据库行的最后一个 ID

Posted

技术标签:

【中文标题】获取最近创建的数据库行的最后一个 ID【英文标题】:Get the last ID of recently created database row 【发布时间】:2021-10-01 16:56:57 【问题描述】:

我正在尝试从数据库表中提取最后插入的 id,以便可以将其输入到新的数据库表中,如下所示:

$mealplaninput =
    MealPlanInput::create([
          'meal_type' => $meal,
          'suitable_for' => $suited,
          'allergens' => $allerg,
          'specific_allergen' => $spec,
          'no_of_people' => $nop,
          'start_date' => $request->date,
          'no_of_days' => $nod,
          'user_id' => $currentuserid,
      ]);

尝试拉取最后一个id(但不起作用):

$uniquemealplanid = $mealplaninput->id();

然后输入到新表中:

MealPlanDisplay::create([
      'MealPlan_ID' => $uniquemealplanid,
      'Day' =>  $recipeday,
]);

但是我得到了错误:

调用未定义的方法 App\Models\MealPlanInput::id()

我也试过其他方法,比如:

$uniquemealplanid =  $this->create($mealplaninput)->id;

但我得到的错误是:

方法 App\Http\Controllers\MealPlanInputController::create 不存在。

如何从 MealPlanInput 中提取最后一个 id?

【问题讨论】:

id 不是属性吗?试试$mealplaninput->id 而不是$mealplaninput->id() 我试过了,不知道为什么,但不幸的是它只是返回 null。 执行dd($mealplaninput); 并检查它实际包含的内容。据我所知,它应该返回填充了 id 的新模型。你的表的主键是id,还是你叫它别的名字? 【参考方案1】:

您需要从模型中创建一个对象以获取 ID。

 $mealplaninput = new MealPlanInput;
    $mealplaninput->meal_type = $meal;
    $mealplaninput->suitable_for = $suited;
    $mealplaninput->allergens = $allerg;
    $mealplaninput->specific_allergen = $spec;
    $mealplaninput->no_of_people = $nop;
    $mealplaninput->start_date = $request->date;
    $mealplaninput->no_of_days = $nod;
    $mealplaninput->user_id = $currentuserid;
    $mealplaninput->save();  
    
    $uniquemealplanid = $mealplaninput->id;
    
       

【讨论】:

发布答案时,请同时添加解释,例如为什么他们应该这样做而不是他们当前的尝试(为什么这不起作用等等)。 根据the manual,::create() 方法应该返回新创建的模型:"或者,您可以使用 create 方法使用单个 php 来“保存”一个新模型语句。插入的模型实例将由create方法返回给您”.【参考方案2】:

你需要尝试

$uniquemealplanid = $mealplaninput->id;

插入

$uniquemealplanid = $mealplaninput->id();

【讨论】:

以上是关于获取最近创建的数据库行的最后一个 ID的主要内容,如果未能解决你的问题,请参考以下文章

获取jqGrid中选择的行的数据

如何获取行的最后更改时间戳?

获取最后插入行的主键 ID 以运行多个插入操作 [重复]

如何获取 MySQL 中最后更新行的 ID?

如何在使用 PHP-PDO 记录查询时获取最后一个插入 ID

从 GridView 获取正在编辑的行的 id