我在這個問題上掙扎了一段時間,找不到解決方案,所以我希望得到一些幫助。Laravel - 得到樹狀結構的計數,其中父數是來自子女的總數
我有兩個相關的模型,ModelOne
也與自己有關,可以有無限數量的子女,孫輩等,並與ModelTwo
有關。
class ModelOne extends Model
{
...
public function model_two()
{
return $this->hasMany(ModelTwo::class, 'foreign_key');
}
//recursively get all children, grandchildren etc.
public function children() {
return $this->hasMany(ModelOne::class, 'foreign_key')->with('children');
}
public function parent() {
return $this->belongsTo(ModelOne::class, 'foreign_key');
}
}
class ModelTwo extends Model
{
...
public function model_one()
{
return $this->belongsTo(ModelOne::class, 'foreign_key');
}
}
在我get函數從ModelOne
我:
public function get($id = null) {
return is_null($id) ?
ModelOne::withCount('model_two')->get() :
ModelOne::withCount('model_two')->where('id', $id)->first();
}
也練就了我的對象好看的一維數組(或一個對象),與相關ModelTwo
計數形式,這是我需要的,但每個相關對象都有個別計數。
我需要的是,每個ModelOne
對象在返回數組中有子女,孫輩等,在該對象中計數是來自其所有子女,孫輩等的計數的總和。 因此,例如,如果我有一個ModelOne
的對象,id = 2,parent_id = 1,計數爲3,另一個對象的id = 3,parent_id = 1,計數爲2,對於id = 1的對象,計數將是5.這個邏輯在所有節點的樹中繼續。
[
{
"id":1
"parent_id":"NULL",
"model_two_count":5
},
{
"id":2
"parent_id":1,
"model_two_count":3
},
{
"id":3
"parent_id":1,
"model_two_count":2
}
...
]