【问题标题】:How I can add atrribute to Laravel model collection?如何向 Laravel 模型集合添加属性?
【发布时间】:2019-09-21 12:52:43
【问题描述】:

我有类别的集合。

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 |空}

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

【问题讨论】:

  • 我实际上并没有完全理解你的问题。您想为集合的元素添加属性吗?您需要对方法进行大量处理的数据是……什么?
  • 这是什么意思:I can't pass data to method with queried data and return it back。请提供您提到的方法。
  • 你想要什么有点混乱。也许更好地解释您当前的方法、当前结果和预期结果。
  • 请出示您的代码。一般来说,迭代所有集合项并添加您想要的属性
  • 我不完全是,但也许 appends 属性是您正在寻找的。 laravel.com/docs/5.8/…

标签: sql database laravel eloquent


【解决方案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": []
  }
]

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    相关资源
    最近更新 更多