Przeglądaj źródła

order-product relation, add products to order

Alexander Musikhin 8 miesięcy temu
rodzic
commit
1d4d805c0c

+ 12 - 0
app/Http/Controllers/OrderController.php

@@ -168,11 +168,23 @@ class OrderController extends Controller
     public function store(StoreOrderRequest $request)
     {
         $data = $request->validated();
+
+        $products = $request->validated('products');
+
+        unset($data['products']);
+
         if(isset($data['id'])) {
             Order::query()->where('id', $data['id'])->update($data);
         } else {
             Order::query()->create($data);
         }
+        if($products) {
+            $order = Order::query()->where('id', $data['id'])->first();
+            $order->products()->sync($products);
+        }
+
+
+
         return redirect()->route('order.index');
     }
 

+ 2 - 6
app/Http/Controllers/ProductController.php

@@ -211,18 +211,14 @@ class ProductController extends Controller
         $s = $request->get('s');
         $searchFields = $this->data['searchFields'];
         $ret = [];
-        if($s && strlen($s > 1)) {
+        if($s) {
             $result = Product::query()->where(function ($query) use ($searchFields, $s) {
                 foreach ($searchFields as $searchField) {
                     $query->orWhere($searchField, 'LIKE', '%' . $s . '%');
                 }
             });
-
             foreach ($result->get() as $p) {
-                $string = '';
-                foreach ($searchFields as $searchField)
-                    $string .= $p->$searchField . ' / ';
-                $ret[$p->id] = $string;
+                $ret[$p->id] = $p->name_tz . ' (арт.' . $p->article . ', №' . $p->nomenclature_number . ', ' . $p->year . 'г., ' . $p->product_price_txt . ')';
             }
         }
         return $ret;

+ 2 - 1
app/Http/Requests/Order/StoreOrderRequest.php

@@ -17,7 +17,7 @@ class StoreOrderRequest extends FormRequest
     /**
      * Get the validation rules that apply to the request.
      *
-     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
+     * @return array
      */
     public function rules(): array
     {
@@ -36,6 +36,7 @@ class StoreOrderRequest extends FormRequest
             'order_status_id'   => 'required|exists:order_statuses,id',
             'tg_group_name'     => 'nullable|string',
             'tg_group_link'     => 'nullable|string',
+            'products'          => 'nullable|array',
         ];
     }
 }

+ 9 - 0
app/Models/Order.php

@@ -6,6 +6,7 @@ use App\Models\Dictionary\Area;
 use App\Models\Dictionary\District;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 use Illuminate\Support\Facades\DB;
 
 class Order extends Model
@@ -28,6 +29,14 @@ class Order extends Model
         'tg_group_link',
     ];
 
+    /**
+     * @return BelongsToMany
+     */
+    public function products(): BelongsToMany
+    {
+        return $this->belongsToMany(Product::class, 'order_product', 'order_id', 'product_id');
+    }
+
     public function user(): BelongsTo
     {
         return $this->belongsTo(User::class, 'user_id', 'id');

+ 5 - 0
app/Models/Product.php

@@ -95,4 +95,9 @@ class Product extends Model
         );
     }
 
+    public function orders()
+    {
+        return $this->belongsToMany(Order::class, 'order_product');
+    }
+
 }

+ 28 - 0
database/migrations/2025_03_30_101937_create_order_product_table.php

@@ -0,0 +1,28 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    /**
+     * Run the migrations.
+     */
+    public function up(): void
+    {
+        Schema::create('order_product', function (Blueprint $table) {
+            $table->id();
+            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
+            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     */
+    public function down(): void
+    {
+        Schema::dropIfExists('order_product');
+    }
+};

+ 23 - 6
resources/views/orders/edit.blade.php

@@ -44,7 +44,12 @@
             <div class="col-xxl-6">
                 <h4>МАФ</h4>
 
-                @include('partials.input', ['name' => 'search_maf', 'title' => 'Поиск МАФ', 'value' => '', 'placeholder' => 'Артикул или номер номенклатуры', 'datalist' => []])
+                @include('partials.input', ['name' => 'search_maf', 'title' => 'Поиск МАФ', 'value' => '',
+                    'placeholder' => 'Артикул или номер номенклатуры', 'datalist' => []])
+                @include('partials.select', ['name' => 'select_maf', 'title' => '', 'options' => [], 'multiple' => true])
+
+                <div id="selected_maf"></div>
+
 
 
             </div>
@@ -63,20 +68,33 @@
 
 @push('scripts')
     <script type="module">
+
+        let selectMaf = $('#select_maf');
         $('#search_maf').on('keyup', function () {
             // search products on backend
             $.get('{{ route('product.search') }}?s=' + $(this).val(),
                 function (data) {
-                    $('#dl-search_maf').children().remove();
+                    selectMaf.children().remove()
                     $.each(data, function (id, name) {
-                        $('#dl-search_maf').append('<option value=\'' + name + '\'>' + id + '</option>');
+                        selectMaf.append('<option value=\'' + id + '\'>' + name + '</option>');
                     });
-                    console.log(data);
                 }
             );
-        })
+        });
 
+        selectMaf.on('change', function () {
+            $('#selected_maf').append('' +
+                '<div class="maf">' +
+                '<input type="hidden" name="products[]" value="'+ $(this).val() +'">' +
+                '<span>'+ $('#select_maf option:selected').text() +'</span> ' +
+                '<i onclick="$(this).parent().remove()" class="bi bi-trash text-danger cursor-pointer"></i>' +
+                '</div>'
 
+            );
+            $('#select_maf').children().remove();
+            $('#search_maf').val('');
+
+        });
 
         $('#district_id').on('change', function () {
             // load areas of selected district
@@ -88,7 +106,6 @@
                     $.each(data, function (id, name) {
                         $('#area_id').append('<option value=\'' + id + '\'>' + name + '</option>');
                     });
-                    console.log(data);
                 }
             );
         });

+ 1 - 0
resources/views/partials/select.blade.php

@@ -6,6 +6,7 @@
     <div class="@if(!($right ?? null)) col-md-8 @endif">
         <select name="{{ $name }}"
                 id="{{ $name }}"
+                @isset($multiple) multiple @endisset
                 class="form-select @error($name) is-invalid @enderror class-{{ $name }}"
                 @required($required ?? null)
                 @disabled($disabled ?? null)>