Laravel加载的关系,动态调用时不允许->count(),除非在@dd()中?



有点奇怪的问题,我可能错过了一些明显的东西。

我有以下对象:

AppModelsCategory {#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" => IlluminateDatabaseEloquentCollection {#2254 ▶}
"translations" => IlluminateDatabaseEloquentCollection {#2212 ▶}
"actions" => IlluminateDatabaseEloquentCollection {#2257 ▼
#items: array:8 [▶]
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
]

在刀片中,使用数组$type在循环中动态调用关系(在本例中为'actions'),该数组在本例中返回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()}},它也可以。

我不明白为什么刀锋不接受{$type['name']}

据我所知,你在一个循环中做你的dd,它在第一个循环中返回8,但是当你运行没有dd的代码时,你会得到错误。这意味着有时$parent_category->{$type['name']}是null,你尝试计数null。

也许你可以试试optional():

{{optional($parent_category->{$type['name']})->count()}}

当它为null时它不会计数你也不会再得到错误了