数据透视表created

数据透视表created

本文介绍了数据透视表created_at上的雄辩过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于将两个表之间具有Eloquent关联关系的两个表的内容相互过滤,这两个表之间有一个Eloquent的AboutToMany().基于这个 SO问题,我提出了以下建议:

I want to filter the contents of two tables which have an Eloquent belongsToMany() to each other based on the created_at column in the pivot table that joins them. Based on this SO question I came up with the following:

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

在这里,我使用一个简单的测试列来检查它是否正常工作,应该为"created_at".

Here I'm using a simple test column to check if it's working, this should be 'created_at'.

但是发生的是,如果ModelA符合 wherePivot()中的条件,我将获得所有具有ModelB信息的ModelA实例.这是有道理的,因为这正是我在告诉它要做的事情.

What happens though is that I get all the instances of ModelA with the ModelB information if it fits the criteria in the wherePivot(). This makes sense because it's exactly what I'm telling it to do.

我的问题是如何限制仅基于数据透视表中的单个列返回的结果?具体来说,我想获取在特定日期之后链接的所有ModelA和ModelB实例.

My question is how do I limit the results returned based on only the single column in the pivot table? Specifically, I want to get all instances of ModelA and ModelB that were linked after a specific date.

推荐答案

好的,到这里了,因为另一个答案仍然是错误的.

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

首先,wherePivotwhereHas闭包中不起作用.这是BelongsToMany的方法,仅在关系对象上起作用(因此在渴望加载时起作用).

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();

这篇关于数据透视表created_at上的雄辩过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 16:56