【问题标题】:Get the last ID of recently created database row获取最近创建的数据库行的最后一个 ID
【发布时间】: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,还是你叫它别的名字?

标签: php sql database laravel eloquent


【解决方案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();

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多