【问题标题】:Getting relationship from children从孩子那里获得关系
【发布时间】:2020-06-17 10:00:42
【问题描述】:

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

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

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

休闲是一个父类别,其中属性category_parent_id 设置为null。 Rental Car 是category_parent_id 设置为Leisure ID 的子类别。交易与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');
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我想总结一个父类别中的所有交易

    如果您总结的意思是合并递归加载的子项的事务,那么您必须保持 transactions 方法原样以递归地加载子项并创建一个单独的方法来进行合并

    这样的事情应该可以工作:

    // 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();
    

    【讨论】:

      猜你喜欢
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2014-11-18
      相关资源
      最近更新 更多