php - Laravel 加载的关系,动态调用将不允许在 Blade 中调用 ->count(),除非在 @dd() 中调用?
问题描述
有点奇怪的问题,我可能遗漏了一些明显的东西。
我有以下对象:
App\Models\Category {#2253 ▼
+guarded: []
+timestamps: false
#connection: "mysql"
#table: "categories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▶]
#original: array:8 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:3 [▼
"children" => Illuminate\Database\Eloquent\Collection {#2254 ▶}
"translations" => Illuminate\Database\Eloquent\Collection {#2212 ▶}
"actions" => Illuminate\Database\Eloquent\Collection {#2257 ▼
#items: array:8 [▶]
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
]
在刀片中,关系(在本例中为“动作”)在循环中使用数组动态调用$type
,在本例中返回actions
,然后返回计数。
{{-- @dd($parent_category->{$type['name']}->count()) --}}
{{$parent_category->{$type['name']}->count()}}
据我了解,这应该完全有效,除了它给出了错误:Call to a member function count() on null
奇怪的是,如果我用注释掉的@dd 检查它,它完全可以正常工作并按8
应有的方式返回!
另外,如果我只是写出来{{$parent_category->actions->count()}}
它也可以。
我不明白为什么 Blade 不接受{$type['name']}
。
解决方案
据我了解,您在循环中执行 dd 并在第一个循环中返回 8 但在没有 dd 的情况下运行代码时会出现错误。这意味着有时$parent_category->{$type['name']}
为空,您尝试指望空。
也许您可以尝试使用 optional():
{{optional($parent_category->{$type['name']})->count()}}
就像那样,当它为空时,它不会尝试计数,并且您不会再收到错误。