2015-12-29 111 views
1

我有兩個表項目畫廊。項目有一個畫廊。在畫廊表中我有一個外鍵project_idLaravel 5的關係hasOne save()?

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"); 

     }); 

在項目模型我有獲取與項目相關的庫函數:

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

當創建新的項目,用戶保存一個新的項目時,從下拉選擇向下圖庫那麼,如何我可以更新畫廊表來使用新創建projects_id

$gallery_id = 2; // user selected gallery 2 

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

回答

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