laravel 在多行和一个循环中插入数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34925773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:04:58  来源:igfitidea点击:

laravel insert data in multiple rows and in one loop

phplaravelblade

提问by Snake

I have an issue in laravel with inserting data in multiple rows. I managed to insert the names in the ingredient table but I would like to add 2 other inputs (unit and quantity).

我在 Laravel 中遇到了在多行中插入数据的问题。我设法在成分表中插入了名称,但我想添加 2 个其他输入(单位和数量)。

Can I do this without creating two more loops ?

我可以在不创建两个循环的情况下执行此操作吗?

Controller:

控制器:

public function store() {

   $meal = new Meal;
   $meal->name = Input::get('name');
   $ingredient_names = Input::get('ingredient_names');
   $meal_ingredients = array();
   foreach($ingredient_names as $ingredient_name)
   {
        $meal_ingredients[] = new Ingredient(array(
            'name'=>$ingredient_name
        ));
   }

    //save  into the DB
    $meal->save();
    $meal->ingredients()->saveMany($meal_ingredients);
}

create.blade.html:

create.blade.html:

    <div class="panel-body">
        {{ Form::open(array('route' => 'meals.store')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', null, array('class' => 'form-control')) }}
            </div>
            <div class="input_fields_wrap">
                <input class="form-control" type="text" name="ingredient_names[]">
                <a class="add_field_button">Ajouter</a>
            </div>


            {{ Form::submit('Valider', array('class' => 'btn btn-primary')) }}
       {!! Form::close() !!}
    </div>

meal.js (just to show you that I am using dynamic fields)

meal.js(只是为了向您展示我正在使用动态字段)

// dynamic fields
var max_fields      = 20; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<div><input class="form-control" type="text" name="ingredient_names[]"/><a href="#" class="remove_field">Supprimer</a></div>'); //add input box
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); x--;
})

回答by Patrick Stephan

Input fields can be arrays. I would recommend that for each ingredient, you have inputs like this:

输入字段可以是数组。我建议对于每种成分,您都有这样的输入:

<div class="row">
    <div class="col-sm-4">
        <div class="form-group">
            {{ Form::label('name', 'Name') }}
            {{ Form::text('ingredient[0][name]', null, array('class' => 'form-control')) }}
        </div>
    </div>
    <div class="col-sm-4">
        <div class="form-group">
            {{ Form::label('unit', 'Unit') }}
            {{ Form::text('ingredient[0][unit]', null, array('class' => 'form-control')) }}
        </div>
    </div>
    <div class="col-sm-4">
        <div class="form-group">
            {{ Form::label('quantity', 'Quantity') }}
            {{ Form::text('ingredient[0][quantity]', null, array('class' => 'form-control')) }}
        </div>
    </div>
</div>

Then, whenever you add a row, increment the ingredient index so that the next row's inputs are like so: ingredient[1][name], etc. Then your store method would look like this:

然后,每当您添加一行时,增加成分索引,以便下一行的输入如下所示:ingredient[1][name]等。那么您的 store 方法将如下所示:

public function store() {
   $meal = new Meal;
   $meal->name = Input::get('name');

   $ingredients = Input::get('ingredient');
   $meal_ingredients = array();

   foreach($ingredients as $ingredient)
   {
        $meal_ingredients[] = new Ingredient(array(
            'name' => $ingredient['name'],
            'unit' => $ingredient['unit'],
            'quantity' => $ingredient['quantity'],
        ));
   }

    //save  into the DB
    $meal->save();
    $meal->ingredients()->saveMany($meal_ingredients);
}

I am not too familiar with the Formclass, so the syntax to get your inputs to be arrays might be slightly different, but essentially, you want to end up with this:

我对这个Form类不太熟悉,所以让你的输入成为数组的语法可能略有不同,但本质上,你想要这样结束:

<input type='text' name='ingredient[0][name]' />