2016-11-09 126 views
0

即時嘗試插入數據到我的股票表至少有2個外鍵,我得到這個錯誤,我不知道我做錯了什麼。SQLSTATE [23000]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗laravel 5.2

這是我的股票模型。

//voorraad = stock 
// Model Voorraad has the attributes, Aantal and Id; 
// foreign keys are Producten_Id and Locaties_Id from the table Producten and locaties table 

class Voorraad extends Model 
{ 
    public $fillable = ['Id', 'aantal', 'Producten_Id', 'Locaties_Id']; 
    protected $table = 'Voorraad'; 

public $timestamps = false; 

public function producten() 
{ 
    return $this->BelongsTo('App\Producten', 'Producten_Id'); 
} 
public function locatie() 
{ 
    return $this->BelongsTo('App\Locatie', 'Locaties_Id'); 
} 
} 

這些是我用來創建和存儲數據到數據庫中的控制器函數。

public function create() 
{  
    //retuning the view with database tables producten and locaties passing through to the create view the Id 

    return view('voorraad.create',[ 
     'producten' => Producten::all('Id'), 
     'locaties' => Locatie::all('Id') 
     ]); 
} 

public function store(Request $request) 
{ 

    //Producten_Id is the foreign key from the table producten 
    //Locaties_Id is the foreign key form the table Locaties 
    //aantal is the ammout of a sertain product 

    Voorraad::create($request->only(['aantal', 'Producten_Id', 'Locaties_Id'])); 



    return redirect(Route('voorraad.index')); 

} 

,這是創建視圖

{!! Form::open(['url'=>'voorraad']) !!} 

{!! Form::label('aantal', 'aantal:') !!} 
{!! Form::text('aantal')!!} </br> 

<div class="form-group"> 
    {{ Form::label('producten_id', 'Producten_Id:') }} 
    {{ Form::Select('Producten_Id' , $producten, null) }}</br> 
</div> 

<div class="form-group"> 
    {{ Form::label('Locatie_Id', 'Id:') }} 
    {{ Form::select('Locaties_Id', $locaties, null) }} 
</div>  
    <div> 
     {!! Form::Submit('create', ['class' => 'btn btn-primary form-control']) !!} 
    </div> 
</div> 

{!! Form :: close()!!}

如果有人能告訴我什麼即時做錯了,我將不勝感激。 如果有什麼我忘記包括只是讓我知道,我會將它添加到問題。

回答

0

首先有很多東西我真的會推薦改變 - 但首先看看這個狀態。

嘗試死亡並轉儲您嘗試從請求中提取的數據。確保你真的擁有你期望擁有的所有數據。我的第一個意思告訴我事端在這裏不見了。

public function store(Request $request) 
{ 
    dd($request->only(['aantal', 'Producten_Id', 'Locaties_Id'])); 
    ... 
} 

即使您可能設法解決這個問題,我強烈建議您對代碼進行重大更改。

public $fillable = ['Id', 'aantal', 'Producten_Id', 'Locaties_Id']; 

永遠不要讓Id可填寫。用戶可以根據自己的喜好更改ID或設置ID。通常你對外鍵也一樣。如laravel文檔中所述,您將它們關聯起來。 https://laravel.com/docs/5.2/eloquent-relationships

$user->account()->associate($account); 

,別讓ID的質量分配!

進行這些更改時,您可能還會輕鬆解決您的外鍵問題。

只是一個簡單的例子

$p = Producten::findOrFail($request->input('Producten_Id')); 
$l = Locatie::findOrFail($request->input('Locaties_Id')); 

$v = new Voorraad(); 
$v->aantal = $request->input('aantal'); 
$v->locatie()->associate($l); 
$v->producten()->associate($p); 

$v->save(); 

通過這個,你將確保$ p和$ L是有效的值,它會以其他方式失敗。

相關問題