【问题标题】:Making a tree with MySQL datas用MySQL数据制作一棵树
【发布时间】:2023-01-03 00:43:31
【问题描述】:

我有一个像这样的 MySQL 表:

+------+-----------------+---------+------------+
| id   | name            | refferal| reference  |
+------+-----------------+---------+------------+
|    1 | Alex Muller     |       1 |       null |
|    2 | John Doe        |       2 |          1 |
|    3 | Tom Foe         |       3 |          1 |
|    4 | Harry Pott      |       4 |          3 |
|    5 | Kate Garry      |       5 |          3 |
|    6 | Mike Blue       |       6 |          4 |
+------+-----------------+---------+------------+

(比这更多的数据......)

我需要使用 Laravel 将该数据转换为 JSON 文件。像这样:

[{"id":1,"name":"Alex Muller","parent":0},
{"id":2,"name":"John Doe","parent":1},
{"id":3,"name":"Tom Foe","parent":1},
{"id":4,"name":"Harry Pott","parent":3},
{"id":5,"name":"Kate Garry","parent":3},
{"id":6,"name":"Mike Blue","parent":4}]

在此之后,我将得到这样的树视图:

TREE

我只是用自己的写法制作了这个 json 文件。我不知道该怎么办。我在等你的答案。谢谢你。

【问题讨论】:

    标签: json laravel


    【解决方案1】:

    在模型上获取您需要的密钥,然后使用 map() 将密钥 reference 更改为 parent,检查 reference 是否为 null 以放入 0,然后使用 json_encode 为 json 数组编码。

    $array = Model::get(['id', 'name', 'reference'])
       ->map(function($model){
            return [
               'id' => $model->id,
               'name' => $model->name,
               'parent' => is_null($reference->reference)? 0 : $reference->reference,
            ];
        })
        ->toArray();
    

    然后只需使用该数组制作一个 json:

    echo json_encode($array);

    【讨论】:

      【解决方案2】:

      如果你想在你的例子中添加额外的字段,比如“parent”,你可以在集合上使用 map :

       $users = User::where(function($query){
        ...
       })->get()->map(function($user){
         return array(
           "id"  => $user->id,
           "name" => $user->name,
           "parent" => *INTEGER*
         );
       })->toJson();
      
      

      或者,如果您只想对模型属性进行编码,则可以直接对集合使用 toJson 序列化:

      $users = User::User::where(function($query){
        ...
       })->get()->toJson();
      

      有关详细信息,请参阅以下链接:

      https://laravel.com/docs/collections

      https://laravel.com/docs/eloquent-serialization#serializing-to-json

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-22
        • 2010-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 2010-10-15
        相关资源
        最近更新 更多