jeudi 30 mars 2017

Laravel: Save a hasOne relationship change

I currently have a relationship between checklistItem and actions as followed:

public function action()
{
     return $this->belongsTo(Action::class, 'action_id', 'id');
}

public function checklistItem()
{
     return $this->hasOne(ChecklistItem::class, 'action_id', 'id');
}

I currently made a method, when saving an action, the checklistItem status should also change depending on what was chosen:

public static function saveFromRequest(Request $request)
    {
        if (($action = parent::saveFromRequest($request)) !== null){

            if (!is_null($action->checklistItem)) {
                $action->checklistItem->value->status = $action->switchStatusChecklist($action);

                //Need to update or save this specific checklistItem
                $action->checklistItem->save();
            }
        }

        return $action;
    }

function switchStatusChecklist($action)
    {
        switch($action->status) {
            case 'closed':
                $status = 'checked';
                break;
            case 'canceled':
                $status = 'notapplicable';
                break;
            default:
                $status = 'open';
                break;
        }
        return $status;
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire