拉拉维尔合并关系

2022-08-30 16:33:54

有没有办法在laravel中合并2个关系?

这是它现在的设置方式,但是有没有办法让两者都合并?

  public function CompetitionsHome() {
    return $this->HasMany( 'Competition', 'home_team_id' );
  }
  public function CompetitionsGuest() {
    return $this->HasMany( 'Competition', 'guest_team_id' );
  }
  public function Competitions() {
    // return both CompetitionsHome & CompetitionsGuest
  }

答案 1

尝试 getter 方法的属性,该方法返回从关系返回的合并集合。

public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}

或者,可以在返回集合之前调用其他方法以获取不同的结果集。

public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    // `latest()` method is shorthand for `orderBy('created_at', 'desc')`
    // method call.
    $competitionsHome = $this->competitionsHome()->latest()->get();
    $competitionsGuest = $this->competitionsGuest()->latest()->get();

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}

答案 2

如果您更喜欢 merge() 方法来组合两个集合(关系),它将覆盖具有相同索引键的元素,因此您将丢失从一个关系中获得的一些数据。

您应该选择 push() 方法,该方法通过将一个集合推送到另一个集合的末尾来创建新的数组键。

下面是一个示例:

public function getCompetitionsAttribute($value) {
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // PUSH ONE TO OTHER!
    return $competitionsHome->push($competitionsGuest);
}

推荐