Home > Software engineering >  Laravel 9 update foreignkey updated_at
Laravel 9 update foreignkey updated_at

Time:07-22

Hi I was wondering how to always set the update_at date correct for a parent node in my database when one of its children is updated. This is my situation :

Parent_table :
  id : 1; updated_at: laraval_date

Child_table :
  id:1;foreign_parent_id:1; updated_at: laraval_date
  id:2;foreign_parent_id:1; updated_at: laraval_date
  id:3;foreign_parent_id:1; updated_at: laraval_date
  id:4;foreign_parent_id:1; updated_at: laraval_date
I would like the parent updated_at to change when one of the children is edited. For example when some edit is made to child 3.

Parent_table :
  id : 1; updated_at: laraval_date

Child_table :
  id:1;foreign_parent_id:1; updated_at: laraval_date
  id:2;foreign_parent_id:1; updated_at: laraval_date
  id:3;foreign_parent_id:1; updated_at: other_date <= some edit made
  id:4;foreign_parent_id:1; updated_at: laraval_date
This would result in :

Parent_table :
  id : 1; updated_at: other_date <= date is updated as well

Child_table :
  id:1;foreign_parent_id:1; updated_at: laraval_date
  id:2;foreign_parent_id:1; updated_at: laraval_date
  id:3;foreign_parent_id:1; updated_at: other_date 
  id:4;foreign_parent_id:1; updated_at: laraval_date
The same should happen when a new child note is added. My solution is rather impracticable and hard to sustain as a child can be edited in many different ways.

Child::where(something is true)->update(something);
Parent::where(something is true)->touch();

Does anyone now how to solve this more elegantly. Perhaps with some sort of eloquent hook. Thanks in advance.

CodePudding user response:

You need to create relationships: https://laravel.com/docs/9.x/eloquent-relationships#touching-parent-timestamps

Something like:

class Child extends Model
{
    protected $touches = ['parent'];

    public function parent()
    {
        return $this->belongsTo(Parent::class, "foreign_parent_id");
    }
}

Then updating Child instance will also update Parent

  • Related