我有两个表项目和图库。项目有一个画廊。在库表中,我有一个外键 project_id 。
Schema::table('galleries', function (Blueprint $table) {
$table->integer("project_id")->unsigned()->nullable()->default(null);
$table->foreign("project_id")
->references("id")
->on("projects")
->onDelete("set null");
});
在Project模型中,我有一个函数可以获得与项目关联的库:
public function gallery()
{
return $this->hasOne("App\Gallery");
}
创建新项目时,用户从下拉菜单中选择,然后在保存新项目时,如何更新库表以使用新创建的项目_id
$gallery_id = 2; // user selected gallery 2
$project = new Project();
$project->title = "new project";
$project->save();
答案 0 :(得分:5)
尝试以下方法:
$gallery_id = 2; // user selected gallery 2
$project = new Project();
$project->title = "new project";
$project->save();
$gallery = Gallery::find($gallery_id);
$gallery->project_id = $project->id;
$gallery->save();