0

I have API data which I get from controller using

return parent::with('children')->get();

it gives me this:

[
   {
      "id":1,
      "name":"George",
      "children":[
         {
            "id":4,
            "parent_id":"1",
            "name":"Glory"
         },
         {
            "id":5,
            "parent_id":"1",
            "name":"Susan"
         }
      ]
   },
   {
      "id":2,
      "name":"Robin",
      "children":[
         {
            "id":9,
            "parent_id":"2",
            "name":"Luke"
         }
      ]
   }
]

I can display it after fetching with axios like this:

    George has 2 children:
        1. Glory
        2. Susan
    Robin has 1 child:
        1. Luke 

Now my goal is to display it like this:

    Name   | parent's name 
    ~~~~~~~~~~~~~~~~~~~~~~~
    Glory  | George
    Susan  | George
    Luke   | Robin 

is there a way to achieve it in vue js or in contoller, models or anyewhere else?

2 Answers 2

0

Define the reverse relationship between Children and Parent, in which you will return the parent model with every children; and then in your controller you return all record that have a non-null parent with their parents

return Model::where("parent_id", "<>", null)->with("parent")->get();

and then in your VueJS app you will have a JSON response of all children models along with their parents.

Sign up to request clarification or add additional context in comments.

8 Comments

these are my current relationships: return $this->belongsTo('App\Models\parent', 'parent_id', 'id'); and return $this->hasMany('App\Models\children');. it gives me new field named parent and all the values are NULL.
are parent and children defined models of your application?
yes. would be easier if the parent model is deleted and move the data to children. but i'm not allowed to do that.
I'm not sure I understand what your problem is anymore! What do you mean by deleting the parent and moving data to children? Note that, as far as I can tell, you are dealing with a recursive relationship, and thus using a single table with recursive relationships would be much more efficient.
that's what i meant move the parent into children. delete the parent table and use only one table.
|
0

I got the answer from here: Select from multiple tables with laravel fluent query builder

so, i changed this:

return parent::with('children')->get();

to this:

  return DB::table('parent')
        ->join('children', 'parent_id', '=', 'parent.id')
        ->get(array(
            'name',
            'parent_name'
        ));

but first i changed the name field in parent table to parent_name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.