如何显示 laravel 消费的嵌套 laravel 查询结果

How to display results of nested laravel query for api consumption

我有一个包含 n 级子类别的类别模型。我希望能够在我的 flutter 应用程序中显示父类别列表。但是我不确定如何查询数据库以将此结果作为 json.

我知道我可以使用下面模型中定义的关系访问 blade 视图中的父类别和子类别,但是当通过 json 将相同数据发送到我的 flutter 应用程序时我该怎么做?

最后,我还希望能够在 flutter 应用程序中执行这样的操作,当我点击一个父类别并且它有子类别时,应该显示子类别列表等等,直到它的最后一个深度.

我的模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = ['id'];

    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id');
    }
}

树行为不是一件容易的事,但幸运的是我以前做过。我将分享我的一些代码。在你的模型中它应该是这样的

class CategoryTree extends Model {
    protected $primaryKey = 'category_tree_id';
    protected $table = 'category_tree';
    

    public function children() {
        return $this->hasMany(self::class, 'parent_id', 'category_tree_id');
    }

    public function parent() {
        return $this->hasOne(self::class, 'category_tree_id', 'parent_id');
    }
}

魔法就在于资源。用 self::collection.

回调集合
class CategoryTreeResource extends JsonResource {
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request) {
        $children = $this->has_children ? $this->children : NULL;
        return [
            'category_tree_id'  => $this->category_tree_id,
            'name'              => $this->name,
            'image_url'         => $this->image_url,
            'has_children'      => $this->has_children,
            'parent_id'         => $this->parent_id,
            'country_id'        => $this->country_id,
            'is_active'         => $this->is_active,
            'order'             => $this->order,
            'children'          => !empty($children) ? self::collection($children) : NULL,
        ];
    }
}

如您所见,它将递归调用资源并为您创建树。这是一个基本示例,您可以在其中更改您想要的任何行为