0

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.

2
  • What have you tried so far? Commented Jul 22, 2022 at 7:16
  • I tried the code mentioned in the post. I haven't tried anything in the form of an eloquent relation as I'm unfamiliar with one that can fix this problem. Sorry if that was unclear. Commented Jul 22, 2022 at 7:19

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.