Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

akvaskov's avatar

Where created_at > $this->created_at in relationship

Hi. I have 3 tables:

  1. products - just a simple table with product ids.
  2. product_checks. regulary, all product are checked if their data is fresh and updated info is stored in this very table. one line per each check. some sort of history of data changes.
  3. prduct_trackers. some users can "subscribe" for some products from specific period of time.

in the product_tracker model i have a relationship:

class ProductTracker extends Model { public function product_checks(): HasMany { return $this->hasMany(ProductCheck::class, 'product_id', 'product_id') ->where('created_at', '>', $this->created_at)); } }

The idea is that: if I call the product_checks relationship, I need to get all checks which were created AFTER a respective tracker was created. I thougth, I can use $this->created_at but $this return null and as result this approach doesn't work.

Just one more remark. I'm talking about a case when product_checks are to be joined being eager loaded using 'with'.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

This might work if you have a single model instance and load its relation, but will never work if you ask for a collection of models since the relations are loaded through a single query and not refering to parent data.

akvaskov's avatar

@Snapey ok, many thanks! yeah, I have realised that works ok with lazy loadng for one model but hoped that it would work with collection of instanses as well. Thank you again!

Please or to participate in this conversation.