【问题标题】:Save multiple rows to database from dynamic forms in Laravel 5在 Laravel 5 中将多行从动态表单保存到数据库
【发布时间】:2015-10-16 05:18:46
【问题描述】:

我正在使用 jQuery 生成两个动态字段。每对字段都显示在页面上,并且可以有多个实例。在提交时(不是 ajax),每对字段与 Auth::id() 一起保存到它们自己的表行中。

HTML 代码中有两个表单,输入两个值,用户单击“添加链接”,然后 jQuery 创建两个隐藏字段(这些是提交的字段),输入的数据以可视方式显示(附加)到#link-list .原来的字段变成空的,这个过程可以重复...

我正在努力创建一个 eloquent 识别的数组以多次保存数据。

我收到错误“未定义索引:链接”或 jQuery 中的第二个输入行。

刀片/HTML:

{!! Form::open(['route' => ['multiple.store'], 'method' => 'post', 'role'=> 'form', 'class' => 'form']) !!}

    <ul id="link-list">
        <!-- append new rows -->
    </ul>

    <div id="newlink" class="form-inline">
        <div class="form-group">
            {!! Form::text('prestore', null, ['placeholder' => 'Store name', 'class' => 'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::text('prelink', null, ['placeholder' => 'Link / URL', 'class' => 'form-control']) !!}
        </div>
        <div class="form-group">
            <button class="btn btn-primary submit new-row" type="button">Add store link</button>
        </div>
    </div>

    <br/><br/>

    {!! Form::submit('Submit rows', ['class' => 'btn btn-success submit']) !!}

{!! Form::close() !!}

jQuery/JavaScript

$(document).on('click', '.new-row', function() {
    var store = $('#newlink input[name=prestore]').val();
    var link = $('#newlink input[name=prelink]').val();
    console.log(store, link);
    $('<li class="not-saved">' +
            '<a href="'+link+'">'+store+'</a>' +
            '<input type="hidden" name="rows[][link]" value="' + link + '">' +
            '<input type="hidden" name="rows[][store]" value="' + store + '">' +
        '</li>').appendTo('#link-list').hide().fadeIn(280);
    $('input[name=prestore]').val('');
    $('input[name=prelink]').val('');
});

控制器:

public function store()
{
    $input = Input::all();

    foreach ($input['rows'] as $row) {
        $items = new Multiple([
            'user_id' => Auth::id(),
            'store' => $row['store'],
            'link' => $row['link'],
        ]);
        $items->save();
    }
}

【问题讨论】:

  • Multiple 是什么类类型? Laravel 的 Model 类没有 saveMany() 方法。
  • 那是我自己的课程,这只是一个测试仓库(测试多行保存,因此得名)。 saveMany() 是我的错误,但我什至无法到达那部分
  • 关于 saveMany(),这是什么? laravel.com/docs/5.1/…
  • 这是HasOneOrManyBelongsToMany 类上的saveMany() 方法,而不是模型本身。如果您在模型上设置了HasManyBelongsToMany 关系,则可以像$myModel-&gt;myRelationship()-&gt;saveMany($arrayOfRelatedModels) 一样使用它。
  • 酷 - 我会记住这一点。但是我仍然无法解决我原来的问题:/

标签: php jquery laravel laravel-5 eloquent


【解决方案1】:

如果这对其他人有帮助,这是处理 Ben 正确答案所需的 jQuery:

var count = 0;

$(document).on('click', '.new-row', function() {

    count++;

    var store = $('#newlink input[name=prestore]').val();
    var link = $('#newlink input[name=prelink]').val();

    if ($('input[name=prestore]').val().length > 2 && $('input[name=prelink]').val().length > 2) {

        $('<li class="not-saved">' +
            '<a href="' + link + '">' + store + '</a>' +
            '<input type="hidden" name="rows[' + count + '][store]" value="' + store + '">' +
            '<input type="hidden" name="rows[' + count + '][link]" value="' + link + '">' +
            '</li>').appendTo('#link-list').hide().fadeIn(280);

        $('input[name=prestore]').val('');
        $('input[name=prelink]').val('');

    } else {

        console.log('At least 3 characters for each field required!');

    }

});

我还添加了一点验证,因此它不会附加空字段

【讨论】:

    【解决方案2】:

    我同意这是您的元素名称的问题,但不同意 Ben 的解决方案。您可以保持 JavaScript 原样并在 PHP 中处理:

    public function store()
    {
        $rows = Input::get('rows');
    
        $userId = Auth::id();
        for ($i = 0; $i < (count($rows) - 1); $i += 2) {
            $item = new Multiple([
                'user_id' => $userId,
                'link'    => $rows[$i]['link'],
                'store'   => $rows[$i + 1]['store'],
            ]);
            $item->save();
        }
    }
    

    【讨论】:

    • 感谢您的回复,我希望这会在 jQuery 修复上起作用(因为它看起来确实更干净),但我得到了同样的错误“未定义的索引:链接”并且最佳答案已经奏效。
    【解决方案3】:

    一个问题在于您的 JavaScript 元素名称:

    <input type="hidden" name="rows[][link]" value="' + link + '">
    <input type="hidden" name="rows[][store]" value="' + store + '">
    

    这将生成$rows 喜欢:

    [
        0 => ["link" => "foo"], 
        1 => ["store" => "bar"]
    ]
    

    但是您的 PHP 代码期望 $rows 类似于:

    [
        0 => [
            "link" => "foo",
            "store" => "bar"
        ], 
        1 => [
            "link" => "foo",
            "store" => "bar"
        ]
    ]
    

    生成预期值的一种方法是在元素中指定行键:

    <input type="hidden" name="rows[0][link]" value="' + link + '">
    <input type="hidden" name="rows[0][store]" value="' + store + '">
    <input type="hidden" name="rows[1][link]" value="' + link + '">
    <input type="hidden" name="rows[1][store]" value="' + store + '">
    

    显然,鉴于您提供的代码,这有点棘手,所以如果您需要帮助,请告诉我。

    【讨论】:

    • 谢谢,明天我什么时候回来看看我的电脑。这确实有道理。听起来我需要在 jquery 中为每个(对)输入进行计数。无论哪种方式,我都会告诉你。
    • 这有效(尽管我在开发工具中手动添加了计数),但它确实成功保存了所有条目。现在我只需要弄清楚如何建立一个计数:)
    猜你喜欢
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2022-06-10
    • 2018-12-17
    相关资源
    最近更新 更多