php 在同一表单中插入多个表的数据

z31licg0  于 2023-05-05  发布在  PHP
关注(0)|答案(1)|浏览(114)

我创建了一个客户模块,它由两个表组成,一个客户表(用于公司)和一个PIC表(用于为一个客户数据添加多个PIC数据)。
在“创建客户”页中,有一些字段可用于将数据发送到:
customer表,包括name、npwp、file_path(公司徽标)和address。PIC表也用PIC_name、PIC_email和PIC_phone更新。网站工作正常,当我没有添加客户数据与图片。但是,当我添加客户数据并单击“创建客户”按钮时,页面只显示正在加载,并显示“超过60秒的最大执行时间”错误消息。但是,客户和图片的数据已添加到MySQL数据库。一段时间后,网站变得很慢。
我试着从pic表中删除数据,只保留客户数据,然后网站又正常工作了。
控制器:

public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'npwp' => 'required|digits_between:15,16|numeric',
            'address' => 'required',
            'file_path' => 'image|file|mimes:png,jpeg,jpg|max:2048',
            'pic_name.*' => 'required',
            'pic_email.*' => 'required|email:rfc,dns',
            'pic_phone.*' => 'required|numeric|digits_between:10,13'
        ]);

        $customer = new Customer;
        $customer->name = $request->input('name');
        $customer->npwp = $request->input('npwp');
        $customer->address = $request->input('address');
        $customer->user_id = auth()->user()->id;

        if ($request->file('file_path')) {
            $file = $request->file('file_path');
            $customerName = str_replace(' ', '_', strtolower($request->input('name')));
            $filename = $customerName . '_' . str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT) . '.' . $file->getClientOriginalExtension();
            $filePath = $file->storeAs('customers-images', $filename, 'public');
            $customer->file_path = $filePath;

            Storage::disk('public')->put($filePath, file_get_contents($file));
        }

        $customer->save();

        $personsInCharge = [];
        $picNames = $request->input('pic_name');
        $picEmails = $request->input('pic_email');
        $picPhones = $request->input('pic_phone');

        $count = min(count($picNames), 5);
        for ($i = 0; $i < $count; $i++) {
            if (!empty($picNames[$i]) && !empty($picEmails[$i]) && !empty($picPhones[$i])) {
                $personInCharge = new PersonInCharge([
                    'pic_name' => $picNames[$i],
                    'pic_email' => $picEmails[$i],
                    'pic_phone' => $picPhones[$i]
                ]);

                $personsInCharge[] = $personInCharge;
            }
        }

        $customer->personInCharge()->saveMany($personsInCharge);

        return redirect()->route('customers.index')->with('success', "Customer added successfully!");
    }

叶片

<form method="POST" action="{{ route('customers.store') }}" enctype="multipart/form-data">
     @csrf
     <div class="row">
         <div class="col-lg-3 mb-2">
             <label for="name" class="form-label">Name</label>
              <input value="{{ old('name') }}" type="text" class="form-control @error('name') is-invalid @enderror" name="name" placeholder="Company Name" autofocus required>
              @error('name')
                  <span class="invalid-feedback text-left" role="alert">
                       <strong>{{ $message }}</strong>
                   </span>
              @enderror
          </div>
          <div class="col-lg-3 mb-2">
             <label for="npwp" class="form-label">NPWP</label>
              <input value="{{ old('npwp') }}" type="text" class="form-control @error('npwp') is-invalid @enderror" name="npwp" placeholder="Without (-)" required>
                @error('npwp')
                    <span class="invalid-feedback text-left" role="alert">
                         <strong>{{ $message }}</strong>
                     </span>
                 @enderror
             </div>
             <div class="col-lg-3 mb-2">
                <label for="image" class="form-label mb-2">Picture</label>
                 <input id="image" name="file_path" type="file" class="form-control @error('file_path') is-invalid @enderror" onchange="previewImage()" accept="image/*" required>
                 @error('file_path')
                      <span class="invalid-feedback text-left" role="alert">
                          <strong>{{ $message }}</strong>
                       </span>
                   @enderror
                </div>
                <div class="col-lg-3 mb-2">
                   <img class="img-preview img-fluid col-lg-5" style="display:none;">
                 </div>
              </div>
              <div class="row">
                 <div class="col-lg-3 mb-4">
                    <label for="address" class="form-label">Address</label>
                    <textarea id="address" name="address" class="form-control" data-height="100">{{ old('address') }}</textarea>
                    @if ($errors->has('address'))
                        <span class="text-danger text-left">{{ $errors->first('address') }}</span>
                     @endif
                  </div>
                  <div class="col-lg-9">
                     <div id="pic-container">
                         <div class="pic">
                            <label for="pic_name[]" class="form-label">Person In Charge</label>
                            <div class="row mb-2">
                                <div class="col-lg-3">
                                     <input value="" type="text" class="form-control @if($errors->has('pic_name[]')) is-invalid @endif" name="pic_name[]" placeholder="PIC Name" required>
                                      @if ($errors->has('pic_name[]'))
                                          <span class="text-danger text-left">{{ $errors->first('pic_name[]') }}</span>
                                       @endif
                                    </div>
                                    <div class="col-lg-3">
                                        <input value="" type="email" class="form-control @if($errors->has('pic_email[]')) is-invalid @endif" name="pic_email[]" placeholder="PIC Email address" required>
                                         @if ($errors->has('pic_email[]'))
                                              <span class="text-danger text-left">{{ $errors->first('pic_email[]') }}</span>
                                          @endif
                                      </div>
                                      <div class="col-lg-3">
                                          <input value="" type="text" class="form-control @if($errors->has('pic_phone[]')) is-invalid @endif" name="pic_phone[]" placeholder="62xxxxxxxxx" required>
                                              @if ($errors->has('pic_phone[]'))
                                                  <span class="text-danger text-left">{{ $errors->first('pic_phone[]') }}</span>
                                              @endif
                                           </div>
                                           <div class="col-lg-3">
                                               <button type="button" class="btn btn-success mt-1 add-pic"><i class="fa-solid fa-plus"></i></button>
                                           </div>
                                         </div>
                                      </div>
                                   </div>
                              </div>
                          </div>
                          <button type="submit" class="btn btn-primary">Create Customer</button>
                      </form>

<script>
        function previewImage() {
            const image = document.querySelector('#image');
            const imgPreview = document.querySelector('.img-preview');

            imgPreview.style.display = 'block';

            const oFReader = new FileReader();
            oFReader.readAsDataURL(image.files[0]);

            oFReader.onload = function(oFREvent) {
                imgPreview.src = oFREvent.target.result;
            }
        }
    </script>
    <script>
        $(document).ready(function() {
            // Add new PIC fields
            $('.add-pic').click(function() {
                // Count the number of existing pic elements
                var count = $('.pic').length;

                // Add new pic element only if count is less than 5
                if (count < 5) {
                    var newPic = $('<div>').addClass('pic');
                    var rowDiv = $('<div>').addClass('row mb-4');
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'text',
                        name: 'pic_name[]',
                        placeholder: 'PIC Name',
                        value: "{{ old('pic_name[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_name[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'email',
                        name: 'pic_email[]',
                        placeholder: 'PIC Email address',
                        value: "{{ old('pic_email[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_email[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'text',
                        name: 'pic_phone[]',
                        placeholder: '62xxxxxxxxx',
                        value: "{{ old('pic_phone[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_phone[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<button>').attr({
                        type: 'button',
                        class: 'btn btn-danger mt-1 remove-pic',
                    }).append($('<i>').addClass('fa-solid fa-minus'))));
                    newPic.append(rowDiv);

                    $('#pic-container').append(newPic);
                } else {
                    alert('You can only add up to 5 Person In Charge.');
                }
            });

            // Remove PIC fields
            $(document).on('click', '.remove-pic', function() {
                $(this).closest('.pic').remove();
            });
        });
    </script>

你对我的问题有什么建议或解决方案吗?
感谢您发送编修。

j2datikz

j2datikz1#

把它添加到你的PHP中

ini_set('max_execution_time', 600);

并通过减少查询数量来优化代码。

$personsInCharge = [];
$picNames = $request->input('pic_name');
$picEmails = $request->input('pic_email');
$picPhones = $request->input('pic_phone');

$count = min(count($picNames), 5);
for ($i = 0; $i < $count; $i++) {
    if (!empty($picNames[$i]) && !empty($picEmails[$i]) && !empty($picPhones[$i])) {
        $personsInCharge[] = [
            'customer_id' => $customer->id,
            'pic_name' => $picNames[$i],
            'pic_email' => $picEmails[$i],
            'pic_phone' => $picPhones[$i]
        ];
    }
}

DB::table('persons_in_charge')->insert($personsInCharge);

相关问题