Laravel 与附加的预加载关系 ->where()

Laravel Eager Loading Relation With Additional ->where()

这是我模型中的关系方法:

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

所以,上面的模型和 Table2 都有相同的列,但是可能有很多条目,所以我想过滤两个表共享的第二列,table_1_id.

它似乎在命令行上完美运行,但在预先加载时关系是空的。

如果我从关系方法中删除额外的 ->where(),那么预先加载就会起作用。

我急切加载的方式是

->with('relation.nestedRelation');

我也试过了

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

我刚刚尝试将其添加为属性以查看是否有帮助,但仍然没有任何乐趣。

您可以使用whereColumn()函数:

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

或者您可以使用它:

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

}