欢迎!我在数据库备注和飞行员中有两张桌子,我想显示属于飞行员的笔记。我在notes表中添加了外键,但是当我尝试创建新注释时我遇到了这样的问题:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`notes`, CONSTRAINT `notes_pilot_id_foreign` FOREIGN KEY (`pilot_id`) REFERENCES `pilots` (`id`))
注意型号:
class Note extends Model
{
protected $table = 'notes';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'data', 'zadanie', 'uwagi', 'pilot_id',
];
public function pilot() {
return $this->belongsTo(Pilot::class);
}
}
试点模式:
class Pilot extends Model
{
protected $table = 'pilots';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'phone', 'email',
];
public function note() {
return $this->hasMany(Note::class);
}
}
注意控制器存储方法:
public function store(Request $request)
{
$this->validate($request, [
'data' => 'required',
'zadanie' => 'required',
'uwagi' => 'required',
]);
$note = new Note (array(
'data' => $request->get('data'),
'zadanie' => $request->get('zadanie'),
'uwagi' => $request->get('uwagi'),
));
$note->save();
$note->pilot()->sync($request->get('pilots'));
return redirect()->route('uwagi.index')
->with('success','Uwagi dodane poprawnie');
}
答案 0 :(得分:0)
试试这个 返回$ this-> hasMany(' App \ Note'); 和 试试这个 返回$ this-> belongsTo(' App \ Pilot');
答案 1 :(得分:0)
问题解决了。我只是没有在迁移中删除公钥中的外键。