DB Schema
Model (Table 1)
id, name, code, parent_id ( I have Parent child relation in the same table)
eg:- We have relation (Model Table)
Data
1, abc, asw0001, 0 ( parent)
2,def, asw00000001,1 ( child In the same table)
3,ghi, asw00000002,1 ( child In the same table)
Users (Table 2)
id, name, email, model_id
eg:- We have relation (Users table)
Note: Only child of Model Table is having a user relation, Also One child have has many relation with users tables
Data
1, lmn, lmn@gmailcom, 2
2, opq, opq@gmailcom, 3
Model Class
function children(){ // For Getting Child belongs to a Parent in Model Table
return $this->hasMany(Model::class,'parent_id');
}
public function parent(){ // For Getting Parent belongs to a Child in Model Table
return $this->belongsTo(Model::class,'parent_id');
}
public function users(){
return $this->hasMany(User::class, 'model_id', 'id');
}
MyController Class
public function index(){
Model::withCount(['children'])->with(['children' => function($query){ $query->withCount('users'); }])->get();
}
It gave result like below
{
array:1 [
0 => Model {
attributes: array:7 [
"id" => 1
"name" => "abc"
"code" => "asw0001"
"created_at" => "2021-03-26 09:12:26"
"updated_at" => "2021-03-26 09:13:19"
"deleted_at" => null
"children_count" => 2
]
relations: array:1 [
"children" => {
array:2 [
0 => Model {
attributes: array:7 [
"id" => 1
"name" => "def"
"code" => "asw00000001"
"created_at" => "2021-03-26 09:13:05"
"updated_at" => "2021-04-01 06:03:48"
"deleted_at" => null
"users_count" => 1
]
}
1 => Model {
attributes: array:7 [
"id" => 2
"name" => "ghi"
"code" => "asw00000002"
"created_at" => "2021-03-26 09:13:05"
"updated_at" => "2021-04-01 06:03:48"
"deleted_at" => null
"users_count" => 1
]
}
]
}
]
}
]
}
I want to get result like
{
array:1 [
0 => Model {
attributes: array:7 [
"id" => 1
"name" => "abc"
"code" => "asw0001"
"created_at" => "2021-03-26 09:12:26"
"updated_at" => "2021-03-26 09:13:19"
"deleted_at" => null
"children_count" => 2,
"users_count" => 2
]
}
]
}
Thanks in advanced