[英]Laravel ->get() returning null
I have a collection in Laravel 5.3 that I created after a query, this dd()
is just one item, didn't want to spam to much... 我在查询后在Laravel 5.3中创建了一个集合,此dd()
只是一项,并不想向其发送太多垃圾邮件...
Collection {#950
#items: array:1 [
0 => Callrail {#942
#table: "callrails"
#appends: []
#with: []
#hidden: []
#casts: []
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:2 [
"hourofday" => 1
"calls" => 2
]
#original: array:2 [
"hourofday" => 1
"calls" => 2
]
#relations: []
#visible: []
#fillable: []
#guarded: []
#dates: []
#dateFormat: null
#touches: []
#observables: []
+exists: true
+wasRecentlyCreated: false
#forceDeleting: false
-originalData: []
-updatedData: []
-updating: false
-dontKeep: []
-doKeep: []
#dirtyData: []
}
]
}
EDIT #1: 编辑#1:
Here is the $calls->toJSON()
output: 这是$calls->toJSON()
输出:
[
{
"hourofday":1,
"calls":2
},
{
"hourofday":15,
"calls":1
},
{
"hourofday":16,
"calls":4
},
{
"hourofday":18,
"calls":7
},
{
"hourofday":19,
"calls":2
},
{
"hourofday":20,
"calls":1
},
{
"hourofday":22,
"calls":2
}
]
The problem is, when I try to do: 问题是,当我尝试执行以下操作时:
$i = 0;
while($i != 24) {
$response[] = array(
'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
'y' => $calls->whereStrict('hourofday', $i)->get('calls', 0);
);
$i++;
}
Every value in the $response
always has 0
, or null
if I don't put a default value in. The values exist, they are in the collection, and are properly formatted, but for whatever reason I can't get them. $response
中的每个值始终为0
,如果我不输入默认值,则为null
。这些值存在,它们在集合中,并且格式正确,但是由于任何原因我都无法获取它们。 Is there something I am missing? 我有什么想念的吗?
Current Documentation: 当前文档:
https://www.laravel.com/docs/5.3/collections#method-get https://www.laravel.com/docs/5.3/collections#method-get
EDIT #2: 编辑#2:
Found the answer with help from @Andrej Ludinovskov and the correct answer: 在@Andrej Ludinovskov的帮助下找到了答案,并给出了正确答案:
$i = 0;
while($i != 24) {
// You have to get the first item in the array, then you can use it like normal
$callCount = $calls->whereStrict('hourofday', $i)->first();
$response[] = array(
'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
'y' => ($callCount?$callCount->calls:0)
);
$i++;
}
You have collection of elements and it has keys start from 0 to n. 您具有元素集合,并且键的范围从0到n。 The key 'calls' is a key of an item of this collection. 键“ calls”是此集合项的键。 So your code should look like: 因此,您的代码应如下所示:
$i = 0;
while($i != 24) {
$item = $calls->whereStrict('hourofday', $i)->get(0, null);
$cnt = 0;
if ($item != null) {
$cnt = $item->calls
}
$response[] = array(
'name' => date('g A', strtotime('2016-01-01 '.$i.':00:00')),
'y' => $cnt
);
$i++;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.