1

我有一个要传递给我的视图的集合。有3行:

Collection {#869 ▼
#items: array:3 [▼
0 => Customer {#868 ▼
  #table: "customers"
  #guarded: []
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:10 [▼
    "id" => 17
    "business_id" => 1
    "first_name" => "Bob"
    "last_name" => null
    "email" => null
    "phone" => null
    "sent_at" => null
    "created_at" => "2017-10-03 16:18:30"
    "updated_at" => "2017-10-03 16:18:30"
    "deleted_at" => null
  ]
  #original: array:10 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}
1 => Customer {#867 ▶}
2 => Customer {#866 ▶}
]
}

在这 3 个客户中,其中 1 个有一个“sent_at”列,我想在我的视图中计算该列。我知道您可以在控制器中执行此操作,但我想修改视图中的集合。

我在我看来已经尝试过了,它没有返回任何结果:

$customers_pending = $customers_all->where('sent_at', null);
$customers_pending->count();
dd($customers_pending);

我想我没有完全理解集合并修改它们。$customers_pending 应该返回 = 1

我得到:

Collection {#879 ▼
    #items: []
}
4

2 回答 2

0

通常您应该在查询中添加条件,如下所示:

$customers_pending = Customer::whereNull('sent_at')->get();
return view('your.view')->with(compact('customers_pending');

因为您不想从数据库中获取例如 1000 条记录以仅在视图中显示 2 条。

但是,如果您确实需要在视图中执行此操作,则可以使用它们显示的方式,例如,如果您需要遍历那些您可以执行的客户:

@foreach ($customers_all->whereStrict('sent_at', null) as $customer)
 {{ $customer->name }}
@endforeach

请注意,与它进行比较时null,使用它可能会更好,whereStrict而不是where获得所需的结果

于 2017-10-11T15:40:34.060 回答
0

问题是您不能使用刀片修改视图中的变量。您可以做的事情如下:

@if($customer_all->count() > 0)
    There are {{ $customer_all->where('sent_at', null)->count() }} pending customers.
@endif

一个肮脏的技巧是@php在你的刀片模板中使用:

@php
    $customer_pending = $customer_all->where('sent_at', null);
@endphp

比您可以继续在视图中使用新集合。

于 2017-10-11T15:49:54.953 回答