Ishmael
Ishmael

Reputation: 55

How to update status automaticaly when all relations are done?

I have two models like

Model A { 
   id 
   name 
   is_completed 
}

and

Model B { 
   id 
   name 
   is_completed 
   model_a_id 
}

Model_A have realtion with Model_B as hasMany()

I want to update the is_completed = true of Model_A automatically when all Model_Bs with the same model_a_id are is_completed = true

Could you advice any best approaches to do this?

I would apprecieate any kind of help! Thanks!

Upvotes: 1

Views: 65

Answers (1)

Erich
Erich

Reputation: 2616

You could execute an event closure whenever Model Bs are updated:

class ModelB extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::updated(function ($model_b) {
            if ($model_b->model_a->is_completed) {
                return;
            }
            foreach ($model_b->model_a->model_bs as $model) {
                if (!$model->is_completed) {
                    return;
                }
            }
            $model_b->model_a->update(['is_completed' => true]);
        });
    }
}

Upvotes: 4

Related Questions