与孩子建立关系

时间:2020-03-04 20:17:41

标签: laravel eloquent

在Eloquent中,我有一个Category模型,可以为我的交易定义一些银行对帐单类别。

类别可以是父类别,也可以是子类别。所有归类的交易都与子类别相关:

Leisure
  - Travel
  - Flight
  - Hotel
  - Rental Car
..etc

休闲是父类别,其中属性category_parent_id设置为nullRental Car是一个子类别,其中category_parent_id设置为ID Leisure。交易与Rental Car相关,而不与Travel相关。

我使用parentchildren关系来查找类别的子代或父代,如下所示:

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');
}

1 个答案:

答案 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();