I have a table in the database with navbar menu items, this table has a relationship 1xN with itself, I'm retrieving the data (like: \App\Menu::with(['childs'])->get()
) as:
array(
array(
'id' => 1,
'id_parent' => NULL,
'url' => '/',
'childs' => array ()
),
array(
'id' => 2,
'id_parent' => NULL,
'url' => '/blog',
'childs' => array (
array(
'id' => 3,
'id_parent' => 2,
'url' => 'blog/kitchen',
'childs' => array(
array(
'id' => 4,
'id_parent' => 3,
'url' => 'blog/kitchen/salads',
'childs' => array()
),
array(
'id' => 5,
'id_parent' => 3,
'url' => 'blog/kitchen/soups',
'childs' => array()
),
)
),
)
),
array(
'id' => 3,
'id_parent' => 2,
'url' => '/blog/kitchen',
'childs' => array()
),
array(
'id' => 4,
'id_parent' => 3,
'url' => 'blog/kitchen/salads',
'childs' => array()
),
array(
'id' => 5,
'id_parent' => 3,
'url' => 'blog/kitchen/soups',
'childs' => array()
),
);
What I need:
array(
array(
'id' => 1,
'id_parent' => NULL,
'url' => '/',
'childs' => array ()
),
array(
'id' => 2,
'id_parent' => NULL,
'url' => '/blog',
'childs' => array (
array(
'id' => 3,
'id_parent' => 2,
'url' => 'blog/kitchen',
'childs' => array(
array(
'id' => 4,
'id_parent' => 3,
'url' => 'blog/kitchen/salads',
'childs' => array()
),
array(
'id' => 5,
'id_parent' => 3,
'url' => 'blog/kitchen/soups',
'childs' => array()
),
)
),
)
),
);
If there is an easier way, like; SELECT
directly in the database it would be great, if not, just removing the inner items from the outer layer with PHP is enough.
You should try below query.
\App\Menu::where('id_parent', '=', null)->with(['childs'])->get();
he will ecrase the /
url if he filters through null parent_id
Here is an example of solution using only PHP
// an empty array
$arr = array();
// data you import from the database
$array = \App\Menu::where('id_parent', '=', null)
->with(['childs'])->toArray();
// populate the empty array
$arr[] = array_shift($array);
$arr[] = array_shift($array);
the $array
variable contain the 3 last undesired occurrences, while the $arr
variable contain your desired values.
But I'm not suggesting to you that because you can do it with another way using Collections
use this one time.......i think this will help you
\App\Menu::where('id_parent', '=', null)->with(['childs'])->get();