Filter tree structure based on children length | In below tree structure I want remove the array if the length of children of children is zero.Is there any way without using multiple loop and building new array?
[{
"id": 1,
"name": "XYZ",
"type": 1,
"mapping_id": 1,
"children": [
{
"id": 1,
"name": "XYZ UAE",
"brand_id": 1,
"type": 2,
"mapping_id": 2,
"children": [
{
"id": 1,
"name": "Dubai Airport Free Zone",
"country_id": 228,
"brand_region_id": 1,
"type": 3,
"mapping_id": 3
}
]
},
{
"id": 3,
"name": "test",
"brand_id": 1,
"type": 2,
"mapping_id": 0,
"children": []
}
]
},
{
"id": 2,
"name": "ABC",
"type": 1,
"mapping_id": 0,
"children": [
{
"id": 2,
"name": "ABC Restaurants UAE",
"brand_id": 2,
"type": 2,
"mapping_id": 0,
"children": []
}
]}]
my code to pull data is
$assets = $this->brand
->select('brands.id', 'brands.name', DB::raw('1 as type,IFNULL(supplier_asset_mappings.id,0) as mapping_id'))
->leftJoin('supplier_asset_mappings', function ($join) use ($supplierId) {
$join->on('asset_id', '=', 'brands.id')
->where('supplier_asset_mappings.supplier_id', $supplierId)
->where('supplier_asset_mappings.asset_type', 1);
})
->with(array('children' => function ($query) use ($supplierDeliveryCountries, $supplierId) {
$query->select('brand_regions.id', 'brand_regions.name', 'brand_id', DB::raw('2 as type,IFNULL(supplier_asset_mappings.id,0) as mapping_id'))
->leftJoin('supplier_asset_mappings', function ($join) use ($supplierId) {
$join->on('asset_id', '=', 'brand_regions.id')
->where('supplier_asset_mappings.supplier_id', $supplierId)
->where('supplier_asset_mappings.asset_type', 2);
})
->where('status', '=', BrandRegion::STATUS_ACTIVE);
}, 'children.children' => function ($query) use ($supplierDeliveryCountries, $supplierId) {
$query->select('branches.id', 'branches.name', 'country_id', 'brand_region_id', DB::raw('3 as type,IFNULL(supplier_asset_mappings.id,0) as mapping_id'))
->leftJoin('supplier_asset_mappings', function ($join) use ($supplierId) {
$join->on('asset_id', '=', 'branches.id')
->where('supplier_asset_mappings.supplier_id', $supplierId)
->where('supplier_asset_mappings.asset_type', 3);
})
->where('branches.location_type', '=', 1)//location type is 1 for branch
->whereIn('country_id', $supplierDeliveryCountries)
->where('status', '=', Branch::STATUS_ACTIVE);
}))
->where('brands.company_id', $companyId)
->where('brands.status', '=', Brand::STATUS_ACTIVE)
->get();
here I am using with
function with array of relationship to get the tree structure.