Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

如何在LARAVEL里优雅的修改输出的JSON的KEY

我有两个MODEL

Product:

protected $visible = ['modules', 'id','name'];
public function modules()
    {
        return $this->hasMany('AppModelModule','root','id');
    }

Module:

protected $visible = [ 'id','name'];

在控制器里:

$products = $this->product->with(['modules'])->get();

输出:
图片描述

前端使用的是iview,我想用iview的级联选择
格式要求是:
clipboard.png

所以求问,在LARAVEL里,如何优雅的修改json的key,以达到我的需求?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

学会map方法,会方便很多

$products->transform(function($value) {
    return [value=>$value->id, 
                label=>$vale->name,
                children=>$value->modules->map(function($v) {return [label=>$v->name,value=>$v->id];})
               ];
});
return $products->toJson();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...