Laravel Collection,键/值相等

时间:2017-10-11 15:34:16

标签: php laravel laravel-5 eloquent laravel-collection

我有一个我传递给我的视图的集合。共有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 ▶}
]
}

在这三个客户中,有一个客户中有一个" sent_at"我希望在视图中计算的null列。我知道你可以在控制器中执行此操作,但我想在视图中修改集合。

我在我的视图中尝试了这个并且它没有返回任何结果:

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

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

我明白了:

Collection {#879 ▼
    #items: []
}

2 个答案:

答案 0 :(得分: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来获得所需的结果

答案 1 :(得分: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

比你可以继续在视图中使用你的新系列。