【问题标题】:Laravel 6: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsLaravel 6:完整性约束违规:1452 无法添加或更新子行:外键约束失败
【发布时间】:2020-04-17 04:20:07
【问题描述】:

大家!

我需要一些帮助。我正在 laravel 6 中创建一个 web 应用程序,它允许用户通过 php 表单插入数据,该表单也插入到数据库中。

基本上,我创建一个供应商(它正在工作),我创建一个材料(它也在工作),然后我创建一个采购(引用供应商和材料)。我还有一个 Unit 表来表明材料是 kg、per_unit 等。

这是我的架构:

供应商架构:

Schema::create('suppliers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('reference');
        $table->string('name',255);
        $table->string('address',255);
        $table->text('zip_code')->nullable();
        $table->string('locality');
        $table->text('phone')->nullable();
        $table->text('description')->nullable();
        $table->timestamps();
    });

材料架构:

Schema::create('materials', function (Blueprint $table) {
        $table->increments('id');
        $table->string('reference');
        $table->string('name',255);
        $table->text('description')->nullable();
        $table->integer('quantity');
        $table->integer('quantity_in_use')->default(0);
        $table->string('image_material')->nullable();
        $table->string('image_receipt')->nullable();
        $table->timestamps();
    });

单元架构:

 Schema::create('units', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });

购买模式:

Schema::create('purchases', function (Blueprint $table) {
        $table->increments('id');
        $table->string('reference');
        $table->datetime('date');
        $table->unsignedInteger('supplier_id');
        $table->unsignedInteger('material_id');
        $table->integer('quantity');
        $table->text('description')->nullable();
        $table->double('price_per_unit');
        $table->unsignedInteger('unit_id');
        $table->timestamps();
    });

还有我创建的关系迁移:

Schema::table('purchases', function (Blueprint $table) {
        $table->foreign('supplier_id')->references('id')->on('suppliers');
        $table->foreign('material_id')->references('id')->on('materials');
        $table->foreign('unit_id')->references('id')->on('units');
    });

问题是,每当我尝试创建购买时,都会出现以下错误:

SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(guacamaiateste.purchases,CONSTRAINT purchases_unit_id_foreign FOREIGN KEY (unit_id) 参考units (id)) (SQL: 插入到purchases (reference, date, supplier_id, material_id, description, quantity, price_per_unit0, price_per_unit3, created_at) values (C01, 17-04-2020 00:00:00, 8, 5, Just a purchase, 1, 1, 2020-04-17 04:08:00, 2020-04-17 04:08 :00))

这是我的模型:

class Purchase extends Model{
protected $fillable = ['reference', 'date', 'supplier_id', 'material_id', 'quantity', 'description', 'price_per_unit'];

public function supplier()
{
    return $this->belongsTo('App\Supplier', 'supplier_id');
}

public function material()
{
    return $this->belongsTo('App\Material', 'material_id');
}

public function unit()
{
    return $this->belongsTo('App\Unit', 'unit_id');
}}

还有我的采购总监:

use Illuminate\Http\Request;
use App\Unit;
use App\Purchase;
use App\Supplier;
use App\Material;
use App\Http\Requests\StorePurchase;
use App\Http\Controllers\Controller;

class PurchaseController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $purchases = Purchase::with(['unit', 'supplier', 'material'])->get();

    return view('admin.purchases.index', [
        'purchases' => $purchases,
    ]);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    $units = Unit::all();
    $suppliers = Supplier::all();
    $materials = Material::all();

    return view('admin.purchases.create', [
        'units' => $units,
        'suppliers' => $suppliers,
        'materials' => $materials,
    ]);
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(StorePurchase $request)
{
    $validated = $request->validated();

    $validated['price'] = $validated['price_per_unit'] * $validated['quantity'];

    if (empty($validated['supplier_id'])) {
        $supplier = Supplier::create([
            'reference' => $validated['supplier_reference'],
            'name' => $validated['supplier_name'],
            'address' => $validated['supplier_address'],
            'locality' => $validated['supplier_locality'],
        ]);
        $validated['supplier_id'] = $supplier->id;
    }

    if (empty($validated['material_id'])) {
        $material = Material::create([
            'reference' => $validated['material_reference'],
            'name' => $validated['material_name'],
            'quantity' => $validated['quantity'],
        ]);
        $validated['material_id'] = $material->id;
    }

    Purchase::create($validated);

    return redirect()->route('purchases.index')
        ->with('status', 'Compra registada com sucesso!')
        ->with('status-type', 'success');
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    $units = Unit::all();
    $purchase = Purchase::find($id);
    $suppliers = Supplier::all();
    $materials = Material::all();

    return view('admin.purchases.edit', [
        'units' => $units,
        'purchase' => $purchase,
        'suppliers' => $suppliers,
        'materials' => $materials,
    ]);
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(StorePurchase $request, $id)
{
    $validated = $request->validated();

    $purchase = Purchase::find($id);

    $purchase->update($validated);

    return redirect()->route('purchases.index')
        ->with('status', 'Compra atualizada com sucesso!')
        ->with('status-type', 'success');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    Purchase::destroy($id);

    return redirect()->route('purchases.index')
        ->with('status', 'Compra apagada com sucesso!')
        ->with('status-type', 'success');
}
}

我知道这很广泛,我很抱歉,但我真的需要帮助......这基本上是这个应用程序的全部意义。

【问题讨论】:

  • 能否请您更改外键类型以使用 unsignedBigInteger 作为类型。
  • 您可以尝试在架构中创建外键 ->nullable()

标签: php mysql laravel eloquent


【解决方案1】:

尝试将unit_id 添加到您的$fillable 数组中。发生此错误的原因是您的单位表中不存在 unit_id 的值。它不存在,因为 laravel 无法写入它,因为 unit_id 不在您的可填充数组中(该数组使 laravel 可以访问该表字段)。

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2020-02-17
    • 2014-03-12
    • 2016-10-27
    • 2015-05-25
    • 2014-01-09
    相关资源
    最近更新 更多