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

Jawe031's avatar

Laravel comparing model table date with relation table date

I'm trying to filter out the data in my relation by comparing the created_at of the model and the created_at of the relation.

This is what i tried: ​?` public function entry_goods() { return $this->hasMany('App\EntryAccessionGood', 'norm_id', 'norm_id') ->whereRaw('entry_accession_goods.created_at <= exit_accession_goods.created_at'); } ?owever I am unable to access the exit_accession_goods table at all (this relation is in the ExitAccessionGood model). Is there a way to get access to the table of the model in which the function is located at?

E.g. rows in exit_accession_goods created today should look at rows in entry_accession_goods that were made today or before it. ​?` ->whereRaw('entry_accession_goods.created_at <= exit_accession_goods.created_at');

0 likes
1 reply
prasadchinwal5's avatar

@jawe031 I believe you would have to extract the where clause to a method.

public function entry_goods() {
 return $this->hasMany('App\EntryAccessionGood', 'norm_id', 'norm_id'); 
}

and then another method which would be like

public function myfilter()
{
    return $this->entry_goods()->whereRaw('entry_accession_goods.created_at <= exit_accession_goods.created_at');
}

Then you can get your results like

$model = Mymodel::find(1);
$model->myfilter()->get();

Please or to participate in this conversation.