无法在 jQuery AJAX 中保存关系数据 500(内部服务器错误)

Failed To Save Relationship Data In jQuery AJAX 500 (Internal Server Error)

我试图在没有关系的情况下保存数据并成功,但是当我尝试保存具有一对多关系的数据时,失败并显示 500(内部服务器错误)。

Table

产品型号

public function category()
{
    return $this->belongsToMany('App\Category');
}

/** 
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'id', 'name', 'product_code', 'product_photo'
];

类别模型

public function product() // parent 
{
    // one job only belongs to one type of job
    return $this->belongsToMany('App\Product');
}

/** 
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'id', 'name'
];

控制器

// Save data to table product
    $product = new \App\Product;
    $product->name = $request->get('name');
    $product->product_code = $request->get('code');

    $productCode = \App\Product::where('product_code', '=', $request->get('code'))->first();

    if ($productCode === null) {
        $product->save();

        // Save relationship data between product and categories
        $getCategories = $request->get('categories');
        $productId = DB::table('products')->select('id')->where('product_code', $request->get('code'))->get();
        $theProduct = \App\Product::withTrashed()->findOrFail($productId);
        $theProduct->category()->attach($getCategories);

    }
    

    return response()->json(['success' => 'Product added successfully']);

查看

<select style="width:100%;" placeholder="Select Categories" name="categories[]" multiple
                            id="categories"
                            class="categories form-control {{ $errors->first('categories') ? 'is-invalid' : '' }}"></select>

$('#saveBtnForCreate').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: "{{ route('products.store') }}",
            method: 'post',
            data: {
                name: $('#name').val(),
                code: $('#code').val(),
                categories: $('#categories').val(),
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html(
                        'An error in your input! Make sure the product code is unique'
                    );
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } else {
                    $('.alert-danger').hide();
                    $('.alert-success').show();
                    $('.datatable').DataTable().ajax.reload();
                    setInterval(function() {
                        $('.alert-success').hide();
                        location.reload();
                    }, 2000);
                }
            }
        });
    });

你知道,当我尝试在没有关系(产品名称和产品代码)的情况下保存数据时,它成功了。但是当我试图保存产品和类别之间的关系数据时,它失败了,并显示 500(内部服务器错误)。另外,我无法使用 dd() 来调试查询。有什么解决办法吗?

我找到了解决办法。由于需要一次性插入有关系的新数据,所以需要使用insertGetId方法。该方法会获取最后一次插入数据的id,所以可以使用id来进行关联。

$productName = $request->get('name');
    $productCode = $request->get('code');
        $productId = DB::table('products')->insertGetId(
            [
                'name' => $productName,
                'product_code' => $productCode
            ]
        );

        // Save relationship data between product and categories
        $categoryId = $request->get('categories');
        $theProductId = \App\Product::withTrashed()->findOrFail($productId);
        $theProductId->category()->attach($categoryId);