Eloquent filter on pivot table created_at

我只是一个虾纸丫 提交于 2019-12-02 07:36:08

OK, here it goes, since the other answer is still wrong.

First off, wherePivot won't work in whereHas closure. It's BelongsToManys method and works only on the relation object (so it works when eager loading).

$data = ModelA::with(['relation' => function ($q) use ($someDate) {

    $q->wherePivot('created_at', '>', $someDate);
    // or
    // $q->where('pivot_table.created_at', '>', $someDate);

    // or if the relation defines withPivot('created_at')
    // $q->where('pivot_created_at', '>', $someDate);

}])->whereHas('ModelB', function ($q) use ($someDate) {

    // wherePivot won't work here, so:
    $q->where('pivot_table.created_at', '>', $someDate);

})->get();

You are using Eager Loading Constraints, which constrain only, like you said, the results of the related table.

What you want to use is whereHas:

$data = ModelA::whereHas('ModelB' => function ($q) {
    $q->wherePivot('test', '=', 1);
})->get();

Be aware that ModelB here refers to the name of the relationship.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!