Laravel, how to update two tables with a one-to-one relationship from a single form -


i have these 2 simple models:

class episode extends model {     protected $fillable = ['number', 'language_code', 'published_at'];      function content()     {         return $this->hasone('app\episodecontent');     } }  class episodecontent extends model {     protected $table = 'episodes_content';     protected $fillable = ['episode_id', 'title', 'description'];      function episode()     {         return $this->belongsto('app\episode');     } } 

where every episode has 1 content. could've used single table, thought make sense keep these sets of data separate.

in form, i'd edit episode , content @ same time, after several attempts haven't figured out how.

this i'm doing:

public function update(request $request, $id) {     $rules = [         'number' => 'required',     ];     $this->validate($request, $rules);     $episode = episode::with('content')->findorfail($id);      $episode->published_at = $request->get('published_at');     $episode->number       = $request->get('number');     $episode->content->title       = $request->get('title');      $episode->update();      return redirect('admin/episodes'); } 

this way, nothing changes in episodes_content table.

in attempt, tried this:

    $episode->published_at = $request->get('published_at');     $episode->number       = $request->get('number');     $episode->active       = $request->get('active');      $episodecontent        = new episodecontent;     $episodecontent->title = $request->get('title');      $episode->content()->save($episodecontent); 

this way, new episodes_content row created, while i'd update existing one.

try guess work

$episode = episode::with('content',function($query) use($id){                 $query->where('episode_id',$id);             })->where('id',$id); 

here i'm assuming field name id in parent table , episode_id in child table. let me know if doesn't work.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -