Laravel getAttribute返回未定义的变量pushData



如果我获得所有数据,我的代码会返回未定义的变量$pushData,但当我基于id(只有1个数据(获得它时,它肯定会返回

public function getCategoryAttribute()
{
$baseData   = Category::whereHas('products', function($query) {
$query->where('product_id', $this->id);
})->get();
foreach($baseData as $baseData) {
$pushData[] = [
'name'          => $baseData['name'],
'slug'          => $baseData['slug'],
'description'   => $baseData['description'],
];
}   
return $pushData;
}

有什么想法吗?

另一种方法是使用map:

public function getCategoryAttribute()
{
return Category::whereHas('products', function($query) {
$query->where('product_id', $this->id);
})->get()->map(function(Category $category) {
return $category->only(['name', 'slug', 'description']);
});
}

我为自己修复了

只需添加$pushData = [];在前臂之前

最新更新