【问题标题】:Laravel - How to insert multi-dimensional Array in DBLaravel - How to insert multi-dimensional Array in DB
【发布时间】:2022-12-01 19:51:43
【问题描述】:

I have the array as below;

I'd like to insert each name keys into tableName and get the inserted id. For the steps, each of them will be inserted into another table tableSteps including the last inserted id of the name.

Like as below screenshot.

In my controller,

Here's what I've done so far.

    $instructionsArrays = $request->instructions;
    $max = count($instructionsArrays);

    for ($x = 1; $x <= $max; $x++) {
        foreach($instructionsArrays as $instructionsArray){
            Instruction::updateOrCreate(
                ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
                ['name' => $instructionsArray['name']],
            );
        }
    }

I was able to save sequence numbers but for names it saves only the last name key. And... I'm really lost..

【问题讨论】:

  • why are u using update or create function? Im trying to solve this for you but the part Im missing is why are u using that
  • You ever think about that this happens because all your test values are Some value ?
  • @geertjanknapen I was gonna say that but Im still waiting for him to explain xd
  • Yeah the updateOrCreate does not really make sense, but it's not really the question being asked..
  • @Kneegrows, I'm using updateOrCreate if incase it doesn't exist for that particular Recipe_ID. I can use create or whatever but I have an issue with such.

标签: arrays laravel multidimensional-array eloquent laravel-9


【解决方案1】:

You can achieve what you want from 2 for loops

foreach($request->instructions as $key => $val){
$id = Instruction::insertGetId(
    ['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
    ['name' => $val['name']],
);
$data = []; //bulk insertion
$created_at = now();
foreach($val["steps"] as $step){
    array_push($data, ["header_id" => $id, "name" => $step, "sequence" => $key+1, "created_at" => $created_at]); //why insert sequence when you can obtain it from the relationship?
  }
  Steps::insert($data);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-28
    • 2022-12-27
    • 2022-12-02
    • 2022-12-01
    • 2022-12-02
    • 1970-01-01
    • 2022-12-01
    • 2022-12-28
    相关资源
    最近更新 更多