2016-11-09 132 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是有效的值,它会以其他方式失败。

相关问题