doubi7739 2016-02-19 21:01
浏览 94
已采纳

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:Laravel 5中的外键约束失败

I'm new to laravel and web application development.

I'm developing a project with laravel 5 to have a little problem linking tables, trying to create a product and upload an image generates the following error:

QueryException in Connection.php line 624: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (inventario.uploads, CONSTRAINT uploads_product_id_foreign FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE) (SQL: insert into uploads (image) values (56c7846619fdb.jpg))

This is the ProductController

<?php namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Requests\SaveProductRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;
use App\Category;
use App\Upload;

class ProductController extends Controller {

public function store(SaveProductRequest $request)
    {
        $data = [
            'name'          => $request->get('name'),
            'slug'          => str_slug($request->get('name')),
            'description'   => $request->get('description'),
            'extract'       => $request->get('extract'),
            'price'         => $request->get('price'),
            'quantity'      => $request->get('quantity'),
            'image'         => $request->get('image'),
            'visible'       => $request->has('visible') ? 1 : 0,
            'category_id'   => $request->get('category_id'),
            'provider_id'   => $request->get('provider_id')
        ];

        $product = Product::create($data);

        $data = \Input::file('file')->getMimeType();
        $extension = strtolower(\Input::file('file')->getClientOriginalExtension());
        $image = uniqid().'.'.$extension;
        $path = "images";

        switch ($data)
        {
            case "image/jpeg":
            case "image/png":
            case "image/gif":
            case "application/pdf":
                if (\Request::file('file')->isValid())
                {
                    \Request::file('file')->move($path, $image);
                    $upload = new Upload();
                    $upload->image = $image;
                    $upload->save();
                }
            break;
            default:
        }    

        $message = $product ? 'Producto agregado correctamente!' : 'El producto NO pudo agregarse!';

        return redirect()->route('product.index')->with('message', $message);
    }
}

The Product Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';

    protected $fillable = ['name', 'slug', 'description', 'extract', 'price', 'quantity', 'visible', 'category_id'];


    // Relation with Category
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function upload()
    {
        return $this->belongsTo('App\Upload');
    }

    //Query para buscador
    public function scopeName($query, $name)
    {
        //dd("scope: " . $name);
        $query->where(\DB::raw("CONCAT(name, '', description, '', price, '', quantity)"), "LIKE", "%$name%");
    }
}

Upload Model

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Upload extends Model 
{

    public $timestamps = false;

    protected $table = 'uploads';

    protected $fillable = ['image', 'product_id'];

    protected $hidden = [];

    //Relación con productos
    public function products()
    {
        return $this->hasOne('App\Product');
    }

}

Upload Database Migration

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUploadsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('uploads', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('image', 300);
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                  ->references('id')
                  ->on('products')
                  ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('uploads');
    }

}

Products Database Migration

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('slug');
            $table->text('description');
            $table->string('extract', 300);
            $table->decimal('price', 8, 2);
            $table->string('quantity', 300);        
            $table->boolean('visible');
            $table->integer('category_id')->unsigned();
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('products');
    }

}

Thank someone who can guide me.

  • 写回答

1条回答 默认 最新

  • dqmnueuu459279 2016-02-19 22:43
    关注

    Looking up your code you're trying to save the Upload model without setting a relationship with the parent model (actually the Product model). For saving your Upload setting up the relationship with the Product, do something like this:

    $product->upload()->save($upload);
    

    instead of

    $upload->save();
    

    You'll keep up the constraint between the uploads table's foreign key (product_id) and the parent table (products)

    Just an advice: when working with multiple insert/upload queries on related data, consider the use of the DB:transaction method for performing your queries in a proper transaction.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历