如何将arrribute添加到Laravel模型集合?

时间:2019-05-03 00:48:12

标签: sql database laravel eloquent

我有“类别收藏”。

有了App\Category::all(),我得到:

ID | PARENT_ID | NAME | DEPTH'

1 | 0 | parent1 | 0

2 | 0 | parent2 | 0

3 | 1 | child1 | 1

4 | 2 | child2 | 1

如何将自定义属性(列或方法结果)添加到集合中? 我想在写等时得到的结果:$categories=Category::with('childs');

ID| PARENT_ID | NAME | DEPTH' | CHILDS

1 | 0 | parent1 | 0 | {2 | 1 | child1 | 1 | NULL}

2 | 0 | parent2 | 0 | {3 | 2 | child2 | 1 | NULL}

3 | 1 | child1 | 1 | NULL

4 | 2 | child2 | 1 | NULL

我认为您明白了。我尝试使用Accessors&Mutators,并成功添加了数据等属性。

  

$ category-> childs; //值应为{12 | 10 |名称1 | 1 | NULL}

但是我被卡住了,因为我无法将数据与查询到的数据一起传递给方法并将其返回。我想使用一个表,稍后将leftright列添加到表中以具有树数据库,现在我只是在尝试简单一些-拥有父级并将子级添加到其集合中

1 个答案:

答案 0 :(得分:1)

您应将模型relationship用于其自身:

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $with = ['childs'];

    public function childs()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }
}

CategoryController.php

public function index()
{
    $categories = Category::all();

    return $categories;
}

$categories将根据需要返回结果:

[
  {
    "id": 1,
    "parent_id": 0,
    "name": "parent1",
    "depth": 0,
    "childs": [
      {
        "id": 3,
        "parent_id": 1,
        "name": "child1",
        "depth": 0,
        "childs": []
      }
    ]
  },
  {
    "id": 2,
    "parent_id": 0,
    "name": "parent2",
    "depth": 0,
    "childs": [
      {
        "id": 4,
        "parent_id": 2,
        "name": "child2",
        "depth": 0,
        "childs": []
      }
    ]
  },
  {
    "id": 3,
    "parent_id": 1,
    "name": "child1",
    "depth": 0,
    "childs": []
  },
  {
    "id": 4,
    "parent_id": 2,
    "name": "child2",
    "depth": 0,
    "childs": []
  }
]