ManyToMany relation - how update attribute in pivot table

心已入冬 提交于 2019-12-11 10:24:24

问题


I am now learning to work with pivot tables: https://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

I have WeeklyRoutine model. Each routine has several Activities. The assigned activities are attached in a pivot table activity_routine.

Relation defined in the WeeklyRoutine model:

    return $this->belongsToMany('App\Models\Activity', 'activity_routine', 'routine_id', 'activity_id')->withPivot('done_at')->withTimestamps();
}

it looks like this:

// activity_routine pivot table (relevant columns only)
| id | activity_id | routine_id  | done_at             |
| 34  | 1          | 4           | 2016-04-23 09:27:27 | // *1
| 35  | 2          | 4           | null                | // *2

*1 this activity is marked as done with the code below *2 this activity is not yet done

what I have:

I can update the done_at field in the pivot table, thus making it marked as DONE for the given week (a weeklyroutine_id = 4 in the above code

public function make_an_activity_complete($routineid, $activityid) {

    $date = new \DateTime;


    $object = Routine::find($routineid)->activities()->updateExistingPivot($activityid, array('done_at' => $date));


    return 'done!';
}

what I need

I want to UN-DO an activity. When it is already done, that is when the done_at is not null buc contains a date, make it null.

In other words I need to do the below switch of value, but the proper way:

$pivot = DB::table('activity_routine')->where('routine_id, $routineid)->where('activity_id, $activityid)->first();
if($pivot->done_at != null) {
    $new_val = new \DateTime;
} else {
    $new_val = null;
}
    $object = Routine::find($routineid)->activities()->updateExistingPivot($activityid, array('done_at' => $new_val));

How to do it? I have no clue!

Thx.


回答1:


Your approach seems fine to me. I would probably do it like this.

$routine = Routine::find($routineid);
$activity = $routine->activities()->find($activityid);
$done_at = is_null($activity->pivot->done_at) ? new \DateTime : null;

$routine->activities()->updateExistingPivot($activityid, compact('done_at'));


来源:https://stackoverflow.com/questions/36809209/manytomany-relation-how-update-attribute-in-pivot-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!