多表同表插入数据

问题描述 投票:0回答:1

我创建了一个由两个表组成的客户模块,一个客户表(用于公司)和一个图片表(为一个客户数据添加多个图片数据)。

在创建客户页面中,有用于将数据发送到的字段:

客户表,包括姓名、npwp、file_path(公司标志)和地址。 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>

您对我的问题有什么建议或解决方案吗?

感谢您的回复。

php laravel multiple-tables
1个回答
0
投票

将此添加到您的 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);
© www.soinside.com 2019 - 2024. All rights reserved.