1
votes

This is my relation method in my model:

public function relation()
{
    return $this->belongsTo('App\Table', 'table_2_id', 'table_2_id')->where('table_1_id', $this->table_1_id);
}

So, both the model above and Table2 have the same column, but there is the possibility of many entries, so I want to then filter on a second column that is shared by both tables, table_1_id.

It seems to work perfectly on the command line, but when eager loading the relationship is empty.

If I remove the additional ->where() from the relationship method then the eager loading works.

The way I am eager-loading is by doing

->with('relation.nestedRelation');

I've also tried

->with(['relation' => function ($q) {
    $q->with('nestedRelation');
}])

I've just tried adding it as an attribute to see if that helped but still no joy.

1

1 Answers

1
votes

You can use the whereColumn() function :

->whereColumn('table_1.table_1_id', 'table_2.table_1_id')

Or you can use that :

public function filterRelation(){
     return $this->relation->where('table_1_id', $this->table_1_id);

}