mardi 12 septembre 2017

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

I have these two very 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 basically every Episode has one content. I could've used a single table, but I thought it could make sense to keep these sets of data separate.

In a form, I'd like to edit the Episode and its content at the same time, but after several attempts I haven't figured out how.

This is what 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 the episodes_content table.

In another attempt, I 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, a new episodes_content row is created, while I'd like to update an existing one.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire