0

I am trying to create Laravel/Vue project with two models: Category and Article. Vue part haves tree-view, which will display categories and articles tree. Categories may belong to another categories, Article may belong only to Article. How can i form json tree from these relations?

model Category

public function articles() {
    return $this->hasMany(Article::class);
}
public function childs() {
    return $this->hasMany(Category::class)->union($this->files()->toBase());
}

but it shows The used SELECT statements have a different number of columns, because there is defferent fields in results. One solution i see here is to find every article and post and create array, then jsonify it. Maybe any better solutions?

UPDATE Done it with this code (in api controller):

    public function nodes() {
        $rootCategories = Category::where('category_id', null)->get();
        $out = $this->_nodes($rootCategories);
        return response()->json($out);
    }
    private function _nodes($eCategories) {
        $out = [];
        foreach($eCategories as $cat) {

            $out[$cat->id] = $cat->toArray();
            $out[$cat->id]["type"] = "folder";
            $out[$cat->id]["childs"] = [];
            foreach ($cat->articles as $article) {

                $out[$cat->id]["childs"][$article->id] = $article->toArray();
                $out[$cat->id]["childs"][$article->id]["type"] = "article";
            }
            if ($cat->categories) {
                $out[$cat->id]["childs"] = $out[$cat->id]["childs"] + $this->_nodesCategory($cat->categories);
            }
        }
        return $out;
    }
looqey
  • 3
  • 4
  • 1
    Does this answer your question? [Eloquent Parent-Child relationship on same model](https://stackoverflow.com/questions/34758965/eloquent-parent-child-relationship-on-same-model) – Vlad Nov 14 '22 at 13:56

0 Answers0