neoko's avatar
Level 1

Create relations for model in static::creating

How can i create a relations for model in static::creating, for example this is my code:

static::creating(function ($model) {
     if(isset($model->workingdays)){
                $workingdays = json_decode($model->workingdays, true);
                if($workingdays['workingdays'] == 'weekdays') {
                    $weekdays = ['monday','tuesday','wednesday','thursday','friday'];
                    foreach ($weekdays as $weekday) {
                        $model->workingdays()->create([
                            "day" => $weekday,
                            "start_time" => $workingdays['workingdaysdaysstart'],
                            "end_time" => $workingdays['workingdaysdaysend'],
                            "dayoff" => false
                        ]);
                    }
                }

or maybe i can create this relations in static::create, but how can i pass $model->workingdays json array, to static::create? btw here is error

SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table \"working_days\" violates foreign key constraint \"working_days_company_id_foreign\"\nDETAIL: Key (company_id)=(9a819564-69e1-4760-8721-cccccd89fd65) is not present in table \"companies\"

please help

0 likes
3 replies
krisi_gjika's avatar

"how can i pass $model->workingdays json array, to static::create?" - don't. If $model->workingdays is meant to represent the one to many relation don't overwrite it with your form input so that you can pass this data to your creating event. Create the model, than create the workingDay models in the same place, wrap it in an action class or a service if you want to reuse that code.

Snapey's avatar

Are you wanting to hide this code from your colleagues?

Model observers should be a last resort in such situations.

Beside, you cannot assign child models when the parent has not yet been saved. Hook into the created event instead (if you must)

1 like
kevinbui's avatar

Just a question, you have a workingdays attribute in your model, and also a workingdays table for the relationship. Are you gonna duplicate data in both of them?

Please or to participate in this conversation.