简体   繁体   English

Laravel 5关系hasOne save()?

[英]Laravel 5 relationships hasOne save()?

I have two tables Projects and Galleries . 我有两个表ProjectsGalleries Project has one gallery. 项目有一个画廊。 In galleries table I have a foreign key project_id . 在图库表中,我有一个外键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");

        });

In Project model I have a function that gets the gallery associated with the project: 在项目模型中,我有一个函数来获取与项目关联的图库:

public function gallery()
  {
    return $this->hasOne("App\Gallery");
  }

When creating new project, user selects from drop down the gallery then when saving a new project, how can I update galleries table to use newly created projects_id 在创建新项目时,用户从下拉菜单中进行选择,然后在保存新项目时,如何更新Galleries表以使用新创建的projects_id

$gallery_id = 2; // user selected gallery 2

$project = new Project();
$project->title = "new project";
$project->save(); 

Try the following: 请尝试以下操作:

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM