当保费ID相同时,使用最大生效日期获取记录的Laravel查询范围

3
如果我有两条记录具有相同的保费ID,我希望只获取具有最大生效日期的一条记录。以下是示例记录:

ar

我尝试使用了。
public function scopeEffectiveDate($query)
    {
        $current_date = Carbon::now()->toDateTimeString();
        return $query->where(max('effective_date'), '<=', $current_date);
    } // shows error

并且

public function scopeEffectiveDate($query)
    {
        $current_date = Carbon::now()->toDateTimeString();
        return $query->groupBy('insurance_provider_id')->latest('effective_date')->where('effective_date', '<=', $current_date);
    }

我得到了一个结果,但不是最新的生效日期,它选择了错误的结果。

你需要检查生效日期是否不是当前日期时间吗? - Saad Suri
尝试这个:$query->groupBy('insurance_provider_id')->latest('effective_date')->where('effective_date', '<=', $current_date)->distinct('column_name'); - Prince Kumar Dwivedi
在问题中指定的,@SaadSuri effective_date <= $current_date - guruprasad ks
@PrinceKumarDwivedi 我试过了,不起作用。 - guruprasad ks
1个回答

2
检查以下代码。
public function scopeEffectiveDate($query)
{
    $current_date = Carbon::now()->toDateTimeString();
    return $query->orderBy('effective_date', 'desc')->where('effective_date', '<=', $current_date);
}

我认为如果他使用 effective_date 进行分组,可能会出现相同保险提供商但不同生效日期的情况,因此这种方法可能行不通。 - Prafulla Kumar Sahu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接