2016-02-19 134 views
0

我是laravel和web应用程序开发的新手。SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:Laravel 5中的外键约束失败

我发展与laravel 5项目有链接表的一个小问题,努力创造一个产品和上传图像生成以下错误:

QueryException在Connection.php行624: SQLSTATE [ 23000]:完整性约束违规:1452不能添加或更新子行,外键约束失败(inventariouploads,约束uploads_product_id_foreign外键(product_id)参考文献productsid)ON DELETE CASCADE)(SQL:插入uploadsimage )值(56c7846619fdb.jpg))

这是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); 
    } 
} 

的产品型号

<?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%"); 
    } 
} 

上传模式

<?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'); 
    } 

} 

上传数据库迁移

<?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'); 
    } 

} 

产品数据库迁移

<?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'); 
    } 

} 

谢谢能引导我的人。

+1

您必须将表'products'中的现有product_id定义到列'uploads_product_id_foreign'中。例如:'INSERT INTO uploads('uploads_product_id_foreign','image')VALUES(4,'56c7846619fdb.jpg')' – CIRCLE

回答

1

查找你的代码,你试图保存上传模型,而不需要与父模型(实际上是产品模型)建立关系。为了节省您的上传设置与产品的关系,做这样的事情:

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

,而不是

$upload->save(); 

你会跟不上上传表的外键(产品)之间的约束父表(产品)

只是一个建议:在对相关数据进行多次插入/上载查询时,考虑使用DB:transaction方法在正确的事务中执行查询。

+0

感谢Andrew Reborn为您的时间和回应。 但是性别改变,因为你推荐以下错误: –

+0

调用未定义的方法照亮\数据库\查询\ Builder :: save() –

+0

但通过修改模型解决产品返回$ this-> belongsTo('App \ Upload“) ;以hasOne和Upload返回$ this-> hasOne('App \ Product');归属于 –

相关问题