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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0