在Eloquent中,我有一个Category
模型,可以为我的交易定义一些银行对帐单类别。
类别可以是父类别,也可以是子类别。所有归类的交易都与子类别相关:
Leisure
- Travel
- Flight
- Hotel
- Rental Car
..etc
休闲是父类别,其中属性category_parent_id
设置为null
。 Rental Car
是一个子类别,其中category_parent_id
设置为ID Leisure
。交易与Rental Car
相关,而不与Travel
相关。
我使用parent
和children
关系来查找类别的子代或父代,如下所示:
public function parent()
{
return $this->hasOne( Category::class, 'id', 'category_parent_id' );
}
public function children()
{
return $this->hasMany( Category::class, 'category_parent_id', 'id' );
}
但是,如果我想汇总父类别中的所有交易,该如何解决呢?当前不起作用:
public function transactions()
{
return $this->children()->with('transactions');
}
答案 0 :(得分:-1)
我想总结父类别中的所有交易
如果总结的意思是合并递归加载的子代的事务,则必须保留transactions
方法,以递归方式加载子代并创建一个单独的方法来进行合并< / p>
类似的事情应该起作用:
// In your model
public function getCombinedTransactions(){
$this->load('transactions');
$transactions = collect();
foreach($this->transactions as $child){
$transactions->push($child->getCombinedTransactions());
}
return $collection->flatten()->unique('id'); // I'm assuming you want unique by id here
}
// You can call it like this elsewhere
$parent->getCombinedTransactions();