Laravel |比较两个集合并根据created_at和deleted_at字段回显其属性

时间:2017-05-12 17:44:51

标签: php laravel sorting merge laravel-5.4

我想显示我的贷款管理层级应用程序的活动列表 因此,可以在一天内给予贷款(created_at)或者可以关闭/完成贷款(deleted_at)。

我使用以下方法获取这两个集合:

$new_loans = loan::withTrashed()->where('created_at', '>=', Carbon::today())->get();

$completed_loans = loan::onlyTrashed()->where('deleted_at', '>=', Carbon::today())->get();

我的问题是我想根据创建贷款的时间和贷款何时关闭来动态显示这两个集合的属性。

假设:

    new_loans   | completed_loans

   1 - 10 am    | 3 - 8 am

   2 - 12 am    | 4- 11 am

输出应为:

活动

  • 3 - 8 am,贷款已关闭
  • 1 - 10 am,New Loan
  • 4 - 11 am,贷款已关闭
  • 2 - 12 am,新贷款

我尝试使用foreachifs编写一些逻辑,但它显然是错误的,

    foreach ($new_loans as $new) 
    {
        foreach ($completed_loans as $comp)
         {

            if($comp->deleted_at > $new->created_at)
            {
            echo $new->customer->first_name.'----- New---'.$new->created_at->diffForHumans()."<br>";
            }
            else
            {
            echo $comp->customer->first_name.'----- Completed---'.$comp->deleted_at->diffForHumans()."<br>";
            }

        }
    }

有人可以告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:3)

您可以将整个事物组合到一个查询中,然后对所需顺序的结果进行排序。

您还应该eager loading customer关系,这样您就不会为每个循环执行新的查询。

所有放在一起的内容如下:

$loans = loan::with('customer')
    ->withTrashed()
    ->where('created_at', '>=', Carbon::today())
    ->orWhere(function($query) {
        return $query->whereNotNull('deleted_at')
            ->where('deleted_at', '>=', Carbon::today());
    })
    ->get()
    ->sortBy(function($loan) {
        return $loan->deleted_at === null ? $loan->created_at : $loan->deleted_at;
    });

foreach ($loans as $loan) {
    if($loan->deleted_at === null) {
        echo $loan->customer->first_name.'----- New---'.$loan->created_at->diffForHumans()."<br>";
    } else {
        echo $loan->customer->first_name.'----- Completed---'.$loan->deleted_at->diffForHumans()."<br>";
    }
}