1
欢迎!我在数据库笔记和飞行员中有两张表,我想显示属于飞行员的笔记。我添加外键票据表,但我也有这样的问题,当我尝试创建新注:laravel - 用外键查询
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');
}
您应该在迁移或数据库表上检查外键。 –