Laravel访问器返回整个对象而不是单个字段

时间:2020-06-21 00:45:10

标签: laravel eloquent laravel-6 accessor eloquent-relationship

我在MenuItemCategory之间具有以下关系:

菜单项模型

public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

public function getCategoryNameAttribute()
    {
        return $this->attributes['category_name'] = $this->category->name;
    }

类别模型

public function menuItems()
    {
        return $this->hasMany('App\Models\MenuItem');
    }

现在,从我的控制器中,当返回所有菜单项的列表时,我想返回category_name及其结果。您在上面的代码中注意到,我创建了一个访问器getCategoryNameAttribute来获取名称。

返回控制器中所有菜单项列表的方法是:

public function index()
    {
        $menuItems = $this->menuItem->all();

        foreach ($menuItems as $menuItem) {
            $menuItem['category_name'] = $menuItem->category_name;
        }

        return $menuItems;
    }

如果我在dd($menuItems);之后立即$menuItems = $this->menuItem->all();,就会得到:

[
        "id" => 1
        "name" => "Hailee Ondricka"
        "category_id" => 1
        "side" => 0
        "side_only" => 0
        "description" => "Amet delectus exercitationem neque tenetur aliquam. Et repudiandae nam nam voluptates laboriosam autem. Natus quo quia ea. Explicabo reprehenderit consequatur quia aliquam incidunt."
        "image" => "https://lorempixel.com/640/480/?39201"
        "available" => 0
        "active" => 0
        "created_at" => "2020-06-21 00:41:02"
        "updated_at" => "2020-06-21 00:41:02"
      ]

但是在我要附加category_name的foreach之后,我得到了:

"id" => 1
    "name" => "Krista Donnelly"
    "category_id" => 1
    "side" => false
    "side_only" => false
    "description" => "Sapiente est maiores non voluptatum odio placeat. Cum enim aut odit autem aut autem. Quasi excepturi omnis laborum aut officia tempora accusamus."
    "image" => "https://lorempixel.com/640/480/?96389"
    "available" => true
    "active" => false
    "created_at" => "2020-06-21 00:42:49"
    "updated_at" => "2020-06-21 00:42:49"
    "category_name" => "Dr. Christelle Purdy MD"
    "category" => array:4 [
      "id" => 1
      "name" => "Dr. Christelle Purdy MD"
      "created_at" => "2020-06-21 00:42:49"
      "updated_at" => "2020-06-21 00:42:49"
    ]
  ]

如您在结果中看到的,我得到了category_name,但是我也得到了与该类别关联的整个category对象,为什么?如何防止整个对象被退回?

0 个答案:

没有答案